"async and await make promises easier to write"
async makes a function return a Promise
await makes a function wait for a Promise
Async Syntax
The keyword async
before a function makes the function return a promise:
Example
return "Hello";
}
return Promise.resolve("Hello");
}
Here is how to use the Promise:
function(value) { /* code if successful */ },
function(error) { /* code if some error */ }
);
Example
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):
Example
return "Hello";
}
myFunction().then(
function(value) {myDisplayer(value);}
);
Await Syntax
The keyword await
before a function makes the function wait for a promise:
The await
keyword can only be used inside an async
function.
Example
Let's go slowly and learn how to use it.
Basic Syntax
let myPromise = new Promise(function(myResolve, myReject) {
myResolve("I love You !!");
});
document.getElementById("demo").innerHTML = await myPromise;
}
myDisplay();
Waiting for a Timeout
let myPromise = new Promise(function(myResolve, myReject) {
setTimeout(function() { myResolve("I love You !!"); }, 3000);
});
document.getElementById("demo").innerHTML = await myPromise;
}
myDisplay();
Waiting for a File
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 keywords async
and await
.
The following table defines the first browser version with full support for both:
Chrome 55 | Edge 15 | Firefox 52 | Safari 11 | Opera 42 |
Dec, 2016 | Apr, 2017 | Mar, 2017 | Sep, 2017 | Dec, 2016 |
Practice Excercise Practice now