/    /  Javascript-Async iteration

Javascript-Async iteration

 

The “async” keyword before a function makes the function return a promise.

In javascript, a Promise is an object which ensures to produce of one value in the future. The promise is used for managing and tackling asynchronous operations.

 

Example:

 

async function myFunction() {
 return "Hello";
}

 

Is the same as:

 

async function myFunction() {
 return Promise.resolve("Hello");
}

 

how to use the Promise:

 

myFunction().then(
 function(value) { /* code if successful */ },
 function(error) { /* code if some error */ }
);

 

Example:

 

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript async / await</h2>

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

<script>
function myDisplayer(some) {
 document.getElementById("demo").innerHTML = some;
}

async function myFunction() {return "welcome I2tutorials";}

myFunction().then(
 function(value) {myDisplayer(value);},
 function(error) {myDisplayer(error);}
);</script>

</body>
</html>

 

OUTPUT:

 

JavaScript async / await

welcome I2tutorials

 

Await Syntax: 

 

The function wait for a promise:

 

let value = await promise;

 

Example:

 

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript async / await</h2>

<h1 id="demo"></h1>

<script>
async function myDisplay() {
 let myPromise = new Promise(function(myResolve, myReject) {
  myResolve("HI Hello Welcome !!");
});
 document.getElementById("demo").innerHTML = await myPromise;
}

myDisplay();
</script>

</body>
</html>

 

OUTPUT:

 

JavaScript async / await

HI Hello Welcome !!

 

Waiting for a Timeout:

 

Example:

 

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript async / await</h2>

<p>Wait 3 seconds (3000 milliseconds) for this page to change.</p>

<h1 id="demo"></h1>

<script>
async function myDisplay() {
 let myPromise = new Promise(function(myResolve, myReject) {
  setTimeout(function() { myResolve("welcome to I2tutorials !!"); }, 3000);
});
 document.getElementById("demo").innerHTML = await myPromise;
}

myDisplay();
</script>

</body>
</html>

 

OUTPUT:

 

JavaScript async / await

Wait 3 seconds (3000 milliseconds) for this page to change.

 

welcome to I2tutorials !!