Loading Please Wait...
async and await make promises easier to write
async makes a function return a Promise
await makes a function wait for a Promise
The keyword async before a function makes the function return a promise.
async function myFunction() {
return "Hello";
}
// above code is same as below
function myFunction() {
return Promise.resolve("Hello");
}
Here is how to use the Promise.
async function myFunction() {
return "Hello";
}
myFunction().then(
function(value) {myDisplayer(value);},
function(error) {myDisplayer(error);}
);
Or simpler, since you expect a normal value (a normal response, not an error).
async function myFunction() {
return "Hello";
}
myFunction().then(
function(value) {myDisplayer(value);}
);
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.
let value = await promise;
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.
Very often we will not need a 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();
How you feel about this blog:
Share this blog on:
If you find any error in the turtorials, or want to share your suggestion/feedback, feel free to send us email at: info@lynxsia.com
Contact UsWe are concern with various development process like website design & development, E-commerce development, Software development, Application development, SMS & Bulk SMS Provider, PWA Development, and many more..
Copyright ©
, Lynxsia IT Solutions, All rights reserved