Javascript-await
The keyword await placed before a function, makes the function wait for a promise:
Syntax:
let value = await promise;
await – only be used inside an async function.
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript async / await</h2>
<h1 id="i2"></h1>
<script>
async function myDisplay() {
let myPromise = new Promise(function(myResolve, myReject) {
myResolve("I like I2tutorials !!");
});
document.getElementById("i2").innerHTML = await myPromise;
}
myDisplay();
</script>
</body>
</html>
OUTPUT:
JavaScript async / await I like I2tutorials !!
Waiting for a Timeout:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript async / await</h2>
<p>Wait 3 seconds (3000 milliseconds) for this page to change.</p>
<h1 id="i2"></h1>
<script>
async function myDisplay() {
let myPromise = new Promise(function(myResolve, myReject) {
setTimeout(function() { myResolve("I like i2tutorials !!"); }, 3000);
});
document.getElementById("i2").innerHTML = await myPromise;
}
myDisplay();
</script>
</body>
</html>
OUTPUT:
JavaScript async / await Wait 3 seconds (3000 milliseconds) for this page to change. I like i2tutorials !!