await
Pauses an async function until a promise settles, then returns its value or throws its error.
- Returns
- The value of the fulfilled promise. On rejection, it throws an error.
Example
#const wait = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms))
console.log('Fetching the test result...')
const score = await wait(300, 87)
console.log(`Score: ${score}%`)Definition and usage
#You place the await operator in front of a promise. The async function pauses at that point, and once the promise is fulfilled, await returns its value and the code continues. If the promise is rejected, await throws an error that you catch with a try...catch block.
Only the current function pauses, not the whole page. Meanwhile, the browser keeps handling clicks, animations, and other code. await works inside async functions, and also at the top level of JavaScript modules, as in the examples on this page.
Successive await statements run one after another. If the operations don’t depend on each other, start them together and wait for all of them with await Promise.all([...]). The whole thing then takes as long as the longest operation, not the sum of their times.
Syntax
#const result = await promiseParameters
#promise
a promise or any value
The promise you’re waiting for. A plain value is returned unchanged.
More examples
#const fail = (ms, message) =>
new Promise((_, reject) => setTimeout(() => reject(new Error(message)), ms))
try {
await fail(200, 'Session expired')
console.log('You won’t see this')
} catch (error) {
console.log('Error:', error.message)
}const task = (name, ms) =>
new Promise((resolve) => {
console.log(`start: ${name}`)
setTimeout(() => {
console.log(`end: ${name}`)
resolve(name)
}, ms)
})
console.log('One after another')
await task('profile', 200)
await task('courses', 100)
console.log('In parallel')
await Promise.all([task('profile', 200), task('courses', 100)])Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Don’t forget
awaitbefore calling anasyncfunction. Without it you get a promise instead of a result, and its error won’t reach yourtry...catch. - Start independent operations together and wait for them with
await Promise.all([...])instead of writing severalawaitstatements in a row. awaitwon’t work in a regular function or in a function passed toforEach(). For a loop that waits, usefor...ofinside anasyncfunction.
Related entries
#- async functionDeclares an asynchronous function that always returns a promise and can use the await keyword inside it.
- PromiseAn object representing the result of an operation that will be available in the future: a value on success or an error.
- Promise.all()Waits for every promise to be fulfilled and returns an array of their results. Rejects at the first error.
- try...catchCatches errors thrown in the try block and handles them in catch. The optional finally always runs.
- for...ofWalks the successive values of an iterable object: an array, a string, a Map, a Set, and others.
Spotted a mistake or missing an example? Write to us.