async marks a function that always returns a promise, and await pauses that function until a promise settles, then gives you its value (or throws its error). It lets you write promise-based code top to bottom, with ordinary try/catch, instead of chaining .then() callbacks.
async function loadUser(id) {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return await response.json();
}
Every example below was run in Node.js 18.18; the outputs shown are the real output of that run. If promises themselves are new to you, read JavaScript promises explained first, because async/await is built on them.
What does an async function return?
Always a promise. MDN puts it plainly: if the return value "is not explicitly a promise, it will be implicitly wrapped in a promise." A returned value fulfills the promise; an uncaught exception rejects it.
async function f() { return 42; }
console.log(f());
async function g() { throw new Error("boom"); }
g().catch(e => console.log("caught:", e.message));
Output:
Promise { 42 }
caught: boom
This is the most common surprise: calling an async function does not give you 42, it gives you a promise of 42. To get the value you either await f() inside another async function, or call f().then(...).
What does await actually do?
await takes a promise, suspends the surrounding async function until that promise is fulfilled or rejected, and then:
- if it fulfilled, the
awaitexpression evaluates to the value; - if it rejected, the rejection reason is thrown at that line, exactly as if you had written
throw.
If you await something that is not a promise, such as await 20, MDN says it is converted to an already-resolved promise, so you get 20 back after a short pause.
The function pauses, the program does not. Code that runs before the first await runs synchronously; everything after it runs later:
async function o() {
console.log("1 inside before await");
await null;
console.log("3 after await");
}
o();
console.log("2 after call");
Output:
1 inside before await
2 after call
3 after await
How to handle errors with try/catch
Because a rejected promise throws at the await, the normal error-handling tools work:
async function loadSettings() {
try {
const response = await fetch("/settings.json");
return await response.json();
} catch (err) {
console.error("Could not load settings:", err);
return {}; // fall back to defaults
} finally {
hideSpinner(); // runs on success and on failure
}
}
Note the return await inside the try. Writing return response.json() without await hands the promise back to the caller unsettled, so if parsing fails, the rejection happens after the function has left the try block and this catch never sees it.
If an error escapes every catch, the async function's promise rejects. If nobody handles that rejection, Node.js has crashed the process by default since version 15 (the --unhandled-rejections=throw default), and browsers fire an unhandledrejection event. Running a file that contains only Promise.reject(new Error("nobody caught me")) prints the error with a stack trace and exits with code 1.
Sequential vs parallel: when to use Promise.all
Each await waits for the previous one to finish. That is right when step 2 needs the result of step 1, and wasteful when the operations are independent. Here wait(200, x) is a helper that resolves to x after 200 ms:
const wait = (ms, v) => new Promise(r => setTimeout(() => r(v), ms));
// one after the other
const a = await wait(200, "a");
const b = await wait(200, "b");
// both at once
const [c, d] = await Promise.all([wait(200, "c"), wait(200, "d")]);
Measured in that run, rounded to 100 ms: the sequential version took 400 ms and the Promise.all version 200 ms. With real network requests the saving is the same idea: total time becomes the slowest request instead of the sum of all of them.
Pick the combinator by what you need when something fails:
| Method | Fulfills when | Rejects when |
|---|---|---|
Promise.all | every promise fulfills (array of values) | any one rejects (first reason) |
Promise.allSettled | every promise settles (array of status objects) | never |
Promise.any | the first one fulfills | all reject (AggregateError) |
Promise.race | the first one to settle fulfills | the first one to settle rejects |
The forEach trap: await inside a loop
Array.prototype.forEach ignores the promise your callback returns, so it does not wait:
[1, 2, 3].forEach(async id => {
await wait(10);
console.log("forEach item", id);
});
console.log("forEach returned");
for (const id of [1, 2, 3]) {
await wait(10);
console.log("for...of item", id);
}
console.log("for...of done");
Output:
forEach returned
forEach item 1
forEach item 2
forEach item 3
for...of item 1
for...of item 2
for...of item 3
for...of done
"forEach returned" prints before any item: the loop finished instantly and the work happened afterwards, untracked. Use for...of when items must be handled one at a time, or await Promise.all(ids.map(async id => { ... })) when they can run together. map works because it collects the returned promises into an array you can await.
Top-level await and "await is only valid in async functions"
await is allowed in two places: inside an async function, and at the top level of a module. Put it anywhere else and Node.js 18 refuses to run the file:
SyntaxError: await is only valid in async functions and the top level bodies of modules
Browsers word the same error differently. Three ways to fix it:
- Add
asyncto the enclosing function:async function x() { await ... }. - Make the file a module: rename it to
.mjs, set"type": "module"inpackage.json, or load it with<script type="module">. Then top-levelawaitworks. - In a CommonJS script, wrap the top level in an async function and call it:
main().catch(console.error).
Arrow functions and methods can be async too: const load = async () => { ... } and class Api { async get() { ... } }.
async/await vs .then(): the same code two ways
// .then() chain
function getTitle(id) {
return fetch(`/api/posts/${id}`)
.then(r => r.json())
.then(post => post.title)
.catch(err => "untitled");
}
// async/await
async function getTitle(id) {
try {
const r = await fetch(`/api/posts/${id}`);
const post = await r.json();
return post.title;
} catch {
return "untitled";
}
}
Both return a promise and behave the same way. async/await reads more easily once there are conditions, loops or several intermediate values; short one-step transformations are often just as clear with .then(). You can mix them freely, since an async function's result is an ordinary promise.
If it still doesn't behave
- You see
Promise { <pending> }where you expected data. A missingawait. Find the call that returns a promise and await it. - A
catchdoesn't fire. The failing promise was not awaited inside thetry(look forreturn somePromisewithoutawait, or a call with noawaitat all). - Code runs in the wrong order. Look for
forEach, event handlers or callbacks that start async work nobody waits for. - The process exits with an error you never saw thrown. An unhandled rejection. The stack trace points at where the promise was rejected; how to read a stack trace covers finding the line that matters.
Frequently asked questions
- Does await block the whole program?
- No. await pauses only the async function it is in. While that function waits, the rest of your code, other event handlers and timers keep running. When the awaited promise settles, the function resumes from the line after the await.
- Can I use await outside an async function?
- Only at the top level of a JavaScript module (an .mjs file, a file in a package with "type": "module", or a script tag with type="module"). Inside an ordinary function or a CommonJS file, Node.js reports SyntaxError: await is only valid in async functions and the top level bodies of modules.
- Is async/await faster than using .then()?
- No. async/await is a different way to write the same promise-based code, and both run on the same promises. Speed differences come from how you order the work: awaiting independent operations one after another is slower than starting them together and awaiting Promise.all.
- What happens if I forget to await a promise?
- The function carries on immediately with a pending promise instead of its value, so the next line may see a Promise object where you expected data. If that promise later rejects and nothing handles it, Node.js 15 and later stops the process with the error, and browsers fire an unhandledrejection event.