Search This Blog

Sunday, September 8, 2019

Learn Promise async await in Javascript

<!DOCTYPE html>
<html>
<body>

<p>This example uses the addEventListener() method to attach a click event to a button.</p>

<button id="myBtn">Try it</button>

<p><strong>Note:</strong> The addEventListener() method is not supported in Internet Explorer 8 and earlier versions.</p>

<p id="demo"></p>

<script>
window.addEventListener("load", function(){

});



function execute(a, b, c)
{
  result = a + b;
  console.log(result);
  //c(result);
}
execute(5, 6, function(data)
{
  console.log(data);
});

var promise = new Promise(function(resolve, reject)
{
  //setTimeout(function()
 // {
//     resolve("Success");
 // }, 2000);

  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
     
       resolve(xhttp.response);
    }
};
xhttp.open("GET", "https://5d74dc3dd5d3ea001425b027.mockapi.io/userss", true);
xhttp.send();
 
 
});

promise.then(function(data)
{
 console.log(JSON.parse(data));
}).catch(function(err)
{
 console.log(err);
});


//async function foo()
//{
 // return Promise.resolve(1);
// }
//foo().then(alert);


async function foo()
{
     let promise = new Promise(function (resolve, reject)
{
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
         resolve(xhttp.response);
         }
};
        xhttp.open("GET", "https://5d74dc3dd5d3ea001425b027.mockapi.io/userss", true);
        xhttp.send();


 });
  let result = await promise;
  alert(result);
 }
 foo();


 async function foos()
 {
   try {
        let response = await fetch("https://5d74dc3dd5d3ea001425b027.mockapi.io/userss");
let result = await response.json();

  } catch(e) {
    // catches errors both in fetch and response.json
    alert(e);
  }


   

 }
 foos();
</script>

</body>
</html>

No comments:

Post a Comment

Validating to select in sequencial order using angular

    < input type = "checkbox" (change) = "handleSelectTaskItem($event, taskItem)" [checked] = " taskItem . i...