JavaScript Async
- Previous Page JS Promise
- Next Page DOM Introduction
"async and await make promises easier to write"
async make the function return a Promise
await make the function wait for a Promise
Async syntax
keyword before the function async
make the function return a promise:
example
async function myFunction() { return "Hello"; }
equivalent to:
async function myFunction() { return Promise.resolve("Hello"); }
Here are some methods of using Promise:
myFunction().then( function(value) { /* Code to execute when successful */ }, function(error) { /* Code to execute when an error occurs */ } );
example
async function myFunction() { return "Hello"; } myFunction().then( function(value) {myDisplayer(value);}, function(error) {myDisplayer(error);} );
or even simpler, because you expect a normal value (normal response, not an error):
example
async function myFunction() { return "Hello"; } myFunction().then( function(value) {myDisplayer(value);} );
Await syntax
keyword before the function await
make the function wait for the promise:
let value = await promise;
await
keywords can only be async
used in functions.
example
let's learn how to use it step by step.
basic syntax
async function myDisplay() { let myPromise = new Promise(function(myResolve, myReject) { myResolve("I love You !!"); }); document.getElementById("demo").innerHTML = await myPromise; } myDisplay();
wait for timeout
async function myDisplay() { let myPromise = new Promise(function(myResolve, myReject) { setTimeout(function() { myResolve("I love You !!"); }, 3000); }); document.getElementById("demo").innerHTML = await myPromise; } myDisplay();
wait for the file
async function getFile() { let myPromise = new Promise(function(myResolve, myReject) { let req = new XMLHttpRequest(); req.open('GET', "mycar.html"); req.onload = function() { if (req.status == 200) {myResolve(req.response);} else {myResolve("File not Found");} }; req.send(); }); document.getElementById("demo").innerHTML = await myPromise; } getFile();
Browser Support
ECMAScript 2017 introduced the JavaScript keyword async
and await
.
The following table lists the first browser version to fully support both:
Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|
Chrome 55 | Edge 15 | Firefox 52 | Safari 11 | Opera 42 |
December 2016 | April 2017 | March 2017 | September 2017 | December 2016 |
- Previous Page JS Promise
- Next Page DOM Introduction