Async and Await
async
and await
were introduced in ES2017 to make an asynchronous code looks like a synchronous code (hiding the Promise underneath).
async
Put async
before a function syntax to make it an async function, e.g.:
async function functionName() {...}
async () => {...}
An async
function always returns a Promise. If an async
function throws, then the Promise rejects. Inside an async
function, you can use the await
expression (explained below).
await
You can use the await
expression ONLY inside an async
function.
The await
expression accepts a single Promise (or any value), and halts the execution of the code underneath until that Promise fulfills or rejects.
for–await loop
When you are iterating through an array of promises, you can use the for await
syntax. (This can only be done in an async
function.)
// Instead of writing:
for (const promise of promises) {
const data = await promise;
handle(data);
}
// You can use the for-await shorthand:
for await (const data of promises) {
handle(data);
}
Try–catch with await
Note that unlike regular Promises, you can do try–catch with await
as if they were a synchronous code.
async function getJSON(url) {
try {
const response = await fetch(url);
const body = await response.json();
return body;
} catch (err) {
console.error('Something wrong happened', err);
return undefined;
}
}
References
- JavaScript: The Definitive Guide, 7th Edition (David Flanagan) — Chapter 13. Asynchronous JavaScript