The await keyword can only be used inside an async function. It pauses the function’s execution, waiting for a resolved Promise before continuing.
let value = await promise; |
Let’s take it step by step and learn how to use it.
async function myDisplay() { let myPromise = new Promise(function(resolve, reject) { resolve(“I love You !!”); }); document.getElementById(“demo”).innerHTML = await myPromise; } myDisplay(); |
The two arguments, resolve and reject, are predefined by JavaScript. We don’t create them ourselves; instead, we call one of them when the executor function completes. In many cases, we may not need the reject function. |
async function myDisplay() { let myPromise = new Promise(function(resolve) { resolve(“I love You !!”); }); document.getElementById(“demo”).innerHTML = await myPromise; } myDisplay(); |
async function myDisplay() { let myPromise = new Promise(function(resolve) { setTimeout(function() {resolve(“I love You !!”);}, 3000); }); document.getElementById(“demo”).innerHTML = await myPromise; } myDisplay(); |
async function getFile() { let myPromise = new Promise(function(resolve) { let req = new XMLHttpRequest(); req.open(‘GET’, “mycar.html”); req.onload = function() { if (req.status == 200) { resolve(req.response); } else { resolve(“File not Found”); } }; req.send(); }); document.getElementById(“demo”).innerHTML = await myPromise; } getFile(); |
ECMAScript 2017 introduced the async and await keywords in JavaScript.
The following table shows the first browser version to fully support both features: