async / await
Syntax for writing promise-based code that reads like ordinary sequential code — await pauses only the async function it's inside.
async function f() { const x = await somePromise; }
Purpose
An async function always returns a promise. Inside it, await pauses execution at that line
until the awaited promise settles, then resumes with its resolved value (or throws, if it rejected)
— all without blocking anything outside that function.
Syntax
async function getGreeting() {
try {
const name = await lookUpName();
return `Hello, ${name}!`;
} catch (error) {
console.error('Could not look up name:', error.message);
return 'Hello, stranger!';
}
}
getGreeting().then((greeting) => console.log(greeting));
Behavior notes
awaitcan only be used directly inside anasyncfunction (or, in modern module code, at the top level of a module).- A rejected awaited promise throws inside the
asyncfunction — catch it with an ordinarytry/catch, exactly as with a synchronous throw. - An
asyncfunction’s return value is automatically wrapped in a resolved promise, even if the function body doesn’t explicitly return a promise itself. - Awaiting several independent promises one at a time (
await a(); await b();) runs them sequentially, wasting time if they don’t depend on each other — usePromise.all(see Promise) to run them concurrently instead.
Common mistakes
- Assuming
awaitblocks the entire program rather than just the function it’s in. - Awaiting requests sequentially that could run concurrently with
Promise.all. - Forgetting
awaitbefore a promise-returning call, which leaves you with an unresolvedPromiseobject instead of its eventual value.
Runtime notes
Core ECMAScript (ES2017), identical behavior across every current browser and Node version.