JavaScript Async Await
JavaScript Async Await
The keyword async before a function makes the function return a promise:
Example
async function myFunction() {
return "Hello";
}
function myFunction() {
return Promise.resolve("Hello");
}
myFunction().then(
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);
Example
async function myFunction() {
return "Hello";
}
myFunction().then(
function(value) {myDisplayer(value);},
function(error) {myDisplayer(error);}
);
Await Syntax
The await keyword can only be used inside an async function.
The await keyword makes the function pause the execution and wait for a
resolved promise before it continues:
Example
Basic Syntax
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 pre-defined by JavaScript.
We will not create them, but call one of them when the executor function is
ready.
myDisplay();
myDisplay();