The JavaScript await statement
The await keyword pauses an async function until a promise settles, then resumes with its resolved value. const data = await response.json(). It only works inside an async function (or a module's top level) and turns promise-based code into clean, sequential-looking lines.
Overview
await unwraps a promise. Put it before a promise-returning call and the async function pauses there until the promise resolves, then continues with the resolved value as if it had been there all along. That's what lets you write const user = await getUser() instead of getUser().then(user => ...) — the asynchronous result reads like a normal variable.
It comes with one firm rule: await only works inside an async function (or at the top level of an ES module). Use it in a plain function and you get a syntax error. So await and async always travel together — the async marks the function, the await does the pausing.
If the awaited promise rejects, the await throws, which you catch with a normal try...catch. One performance note: awaiting promises one after another runs them sequentially. When the operations don't depend on each other, start them together and await with Promise.all([...]) so they run in parallel — a frequent and easy speed-up.
Syntax
async function getData() {
const res = await fetch("/api"); // pause until it resolves
const data = await res.json();
return data;
}
// parallel, not sequential
const [a, b] = await Promise.all([fetchA(), fetchB()]);
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const delay = (val, ms) => new Promise(r => setTimeout(() => r(val), ms));
async function run() {
const out = document.getElementById('out');
out.textContent = 'Working...';
const a = await delay('first', 400);
const b = await delay('second', 400);
out.textContent = 'Got: ' + a + ', ' + b;
}
run();
</script>
Best practices
- Use
awaitonly inside an async function (or a module's top level). - Wrap awaited calls in try...catch to handle rejected promises.
- Run independent awaits in parallel with
await Promise.all([...]), not one after another. - Don't
awaitinside forEach() — use a for...of loop for sequential awaiting.
Frequently asked questions
What does await do in JavaScript?
Where can I use await?
async function, or at the top level of an ES module. Using it in a regular function is a syntax error.How do I handle an error from await?
await.How do I await multiple promises at once?
await Promise.all([p1, p2]) to run them in parallel and wait for all to finish.