await
Waits for a promise and returns its value.
Available since: ES2017
Syntax
await promiseExamples
Waiting for a value:
const value = await Promise.resolve('ready');
console.log(value);Output:
readySequentially and in parallel:
const wait = (ms) => new Promise((resolve) => setTimeout(() => resolve(ms), ms));
let start = Date.now();
await wait(100);
await wait(100);
console.log('sequential:', Math.round((Date.now() - start) / 100) * 100, 'ms');
start = Date.now();
await Promise.all([wait(100), wait(100)]);
console.log('parallel:', Math.round((Date.now() - start) / 100) * 100, 'ms');Output:
sequential: 200 ms
parallel: 100 msNotes
await works only inside an async function or at the top level of a module. A rejected promise's error is caught with an ordinary try...catch.
Do not await independent operations one by one — run them together with Promise.all().
See also
- async function — A function that always returns a promise and lets you use await inside.
- Promise — A promise of a result that will be ready later: success or failure.
- Promise.all — Waits for all promises in parallel.
Related recipes
In the tutorial
- async and await — Asynchronous functions in JavaScript: async, await, error handling with try...catch, sequential and parallel waiting.