JavaScript async and await: Writing Asynchronous Code That Reads Like Synchronous Code
Learn async functions and await: what they return, how await pauses only the function, try/catch/finally for errors, return vs return await, sequential vs parallel awaits, loops and the forEach trap, top-level await in modules, async methods, and the mistakes interviewers ask about.
kvi5hnuCode Sprout team member8 min readOn this page
Promise chains (article 96) are flat, but they still split your logic into small callbacks. async functions and the await operator (ES2017) let you write the same logic as ordinary step-by-step code with normal variables, if statements, loops and try...catch. Under the hood it's still promises and the event loop; the syntax just reads better.
// promise chain
function showOrders(id) {
return getUser(id)
.then((user) => getOrders(user))
.then((orders) => render(orders))
.catch(showError);
}
// async/await
async function showOrders(id) {
try {
const user = await getUser(id);
const orders = await getOrders(user);
render(orders);
} catch (err) {
showError(err);
}
}
async functions always return a promise
Putting async before a function changes what it returns:
return valuefulfills the returned promise withvalue.throw errorrejects it witherror.- Returning a promise makes the result follow that promise.
async function getAnswer() {
return 42;
}
async function failLoudly() {
throw new Error("boom");
}
console.log(getAnswer());
getAnswer().then((v) => console.log("value:", v));
failLoudly().catch((err) => console.log("rejected:", err.message));
Promise { 42 }
value: 42
rejected: boom
So a caller of an async function treats it like any other promise-returning function: with await, then or the combinators from article 97. Every form of function can be async:
async function load() {} // declaration
const load2 = async function () {}; // expression
const load3 = async (id) => fetchItem(id); // arrow
const api = { async get(id) {} }; // method
class Store { async save(item) {} static async open() {} }
await pauses the function, not the program
await expr waits for the promise expr to settle. If it fulfills, await evaluates to the value; if it rejects, await throws the reason. While waiting, the async function is suspended and control returns to the caller, so the thread stays free for other work.

async function loadReport() {
console.log("B: runs synchronously, up to the first await");
await null;
console.log("D: resumes later, as a microtask");
}
console.log("A: before the call");
loadReport();
console.log("C: the caller continues immediately");
A: before the call
B: runs synchronously, up to the first await
C: the caller continues immediately
D: resumes later, as a microtask
Two points that interview questions love:
- The body runs synchronously until the first
await. An async function with noawaitstill returns a promise, but its body ran immediately. - Code after
awaitalways runs asynchronously, even when the awaited value isn't a promise (await null,await 5). It's scheduled as a microtask, like athencallback.
await also works on thenables (any object with a then method), which is how libraries with their own promise-like objects interoperate.
Like generators (article 91), an async function is a function that can pause and resume. The difference is who resumes it: a generator waits for the caller's next(), an async function waits for a promise to settle.
Error handling with try...catch
Because a rejected await throws, ordinary try...catch...finally handles async errors, and it covers synchronous bugs in the same block:
const delay = (ms, value) => new Promise((resolve) => setTimeout(resolve, ms, value));
async function loadSettings(online) {
try {
const data = await (online ? delay(5, { theme: "dark" }) : Promise.reject(new Error("offline")));
return data;
} catch (err) {
console.log("using defaults because:", err.message);
return { theme: "light" };
} finally {
console.log("spinner hidden");
}
}
async function main() {
console.log(await loadSettings(true));
console.log(await loadSettings(false));
}
main();
spinner hidden
{ theme: 'dark' }
using defaults because: offline
spinner hidden
{ theme: 'light' }
Guidelines:
- Wrap only the code whose failure you can actually handle. A huge
tryaround everything makes it hard to tell which step failed. - If you can't handle an error, don't catch it: let it reject the async function's promise, and the caller decides.
- At the very top (an event handler, a script's
main()), something must handle the rejection, or you get an unhandled rejection (article 96). A common pattern ismain().catch((err) => { console.error(err); process.exitCode = 1; }). - For a one-off fallback, mixing styles is fine:
const user = await getUser(id).catch(() => guestUser);.
return vs return await
Inside try, the difference matters:
async function withoutAwait() {
try {
return Promise.reject(new Error("escaped the try"));
} catch {
return "caught";
}
}
async function withAwait() {
try {
return await Promise.reject(new Error("ignored"));
} catch {
return "caught";
}
}
async function main() {
console.log(await withoutAwait().catch((err) => "caller got: " + err.message));
console.log(await withAwait());
}
main();
caller got: escaped the try
caught
return promise hands the promise to the caller unsettled, so its rejection happens after the function has left the try. return await promise waits inside the try, so catch (and finally) see the outcome. Outside a try, both behave the same; return await also keeps the function in async stack traces, so many style guides now recommend it consistently.
Sequential vs parallel awaits
Each await waits before the next line runs. That's correct when step 2 needs step 1's result, but a performance bug when the steps are independent:
const delay = (ms, value) => new Promise((resolve) => setTimeout(resolve, ms, value));
const getProfile = () => delay(50, "profile");
const getNotifications = () => delay(50, "notifications");
async function sequential() {
const start = Date.now();
const profile = await getProfile();
const notifications = await getNotifications(); // waits for profile first
return `${profile} + ${notifications}: ${Date.now() - start >= 100 ? "about 100" : "under 100"} ms`;
}
async function parallel() {
const start = Date.now();
const [profile, notifications] = await Promise.all([getProfile(), getNotifications()]);
return `${profile} + ${notifications}: ${Date.now() - start < 90 ? "about 50" : "90+"} ms`;
}
async function main() {
console.log(await sequential());
console.log(await parallel());
}
main();
profile + notifications: about 100 ms
profile + notifications: about 50 ms
Rule of thumb: when the awaits are independent, start them all, then await them together with Promise.all (or allSettled).
Avoid the shortcut of starting promises early and awaiting them one by one (const a = getA(); const b = getB(); await a; await b;). If b rejects while you're still waiting on a, nobody is listening to b yet, which can trigger an unhandled-rejection crash. Promise.all attaches handlers to every promise at once.
Loops and the forEach trap
const delay = (ms, value) => new Promise((resolve) => setTimeout(resolve, ms, value));
const ids = [3, 1, 2];
async function main() {
const fromForEach = [];
ids.forEach(async (id) => {
await delay(id * 5);
fromForEach.push(id);
});
console.log("forEach, right after:", fromForEach);
const sequential = [];
for (const id of ids) {
await delay(id * 5); // one at a time, in order
sequential.push(id);
}
console.log("for...of:", sequential);
const concurrent = await Promise.all(
ids.map(async (id) => {
await delay(id * 5); // all at once
return id * 10;
}),
);
console.log("map + Promise.all:", concurrent);
console.log("forEach, eventually:", fromForEach);
}
main();
forEach, right after: []
for...of: [ 3, 1, 2 ]
map + Promise.all: [ 30, 10, 20 ]
forEach, eventually: [ 1, 2, 3 ]
forEachcalls the async callback and ignores the promise it returns, so nothing waits, results arrive in completion order, and errors become unhandled rejections. The same applies tofilter,someandreducewith async callbacks.for...ofwithawaitruns sequentially. Use it when order matters or each step depends on the last (or to go easy on a server).mapplusPromise.allruns concurrently and keeps input order.
With await, the concurrency-limit helper from article 97 gets much shorter:
const delay = (ms, value) => new Promise((resolve) => setTimeout(resolve, ms, value));
async function mapWithLimit(items, limit, fn) {
const results = new Array(items.length);
let next = 0;
async function worker() {
while (next < items.length) {
const index = next++;
results[index] = await fn(items[index]);
}
}
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
return results;
}
mapWithLimit([1, 2, 3, 4, 5], 2, (n) => delay(5, n * n)).then((r) => console.log(r));
[ 1, 4, 9, 16, 25 ]
Because JavaScript is single-threaded, next++ between awaits can't race: no other worker runs in the middle of it.
Top-level await
In ES modules (article 75), await works at the top level, outside any function:
// config.js (an ES module)
const response = await fetch("/config.json");
export const config = await response.json();
Modules that import config.js wait until it finishes evaluating, so they always see a loaded config. Use it for one-time setup like loading configuration or a dynamic import(), and keep it short: a slow top-level await delays every module that depends on this one. It isn't available in classic scripts or CommonJS, where the usual wrapper is an async main() function.
What happens underneath
It helps to picture an async function as an ordinary function that wraps its body in a promise:
// async function loadName(id) { body } behaves roughly like:
function loadName(id) {
return new Promise((resolve, reject) => {
try {
// run the body; `return x` becomes resolve(x)
} catch (err) {
reject(err); // a synchronous throw becomes a rejection
}
});
}
Each await then splits the body. Everything after it is attached to the awaited promise as if it were a then callback, with the function's local variables preserved between the pieces. Engines actually implement this the way generators work (article 91): the function is suspended at each await and resumed when the promise settles. In fact, before ES2017, libraries emulated async/await with a generator and a small driver that called next(value) on fulfillment and throw(error) on rejection:
function run(generatorFunction) {
return new Promise((resolve, reject) => {
const gen = generatorFunction();
function step(method, input) {
let result;
try {
result = gen[method](input); // resume the generator
} catch (err) {
return reject(err);
}
if (result.done) return resolve(result.value);
Promise.resolve(result.value).then(
(value) => step("next", value), // fulfilled: send the value in
(error) => step("throw", error), // rejected: throw it inside
);
}
step("next");
});
}
const delay = (ms, value) => new Promise((resolve) => setTimeout(resolve, ms, value));
run(function* () {
const user = yield delay(5, "Ana"); // reads like `await`
const count = yield delay(5, 3);
return `${user} has ${count} orders`;
}).then(console.log);
Ana has 3 orders
yield plays the role of await and run plays the role of the engine. Seeing it written out explains three rules from this article: a rejected await throws inside the function, the body before the first await runs synchronously, and the async function's return value fulfills its promise.
async/await and promises are the same thing
await and .then interoperate freely, because async functions take and return ordinary promises:
- An async function can be passed to anything expecting a promise-returning function.
Promise.all,raceandanycombine async calls..then/.catchon an async function's result is perfectly valid.
Pick whichever is clearer in context: await for multi-step logic with branches and loops, a short .then/.catch for one-line transformations or fallbacks.
Common mistakes
- Forgetting
await:const user = getUser(id)gives a promise, souser.nameisundefined. Linters (and TypeScript) flag "floating" promises. - Using
awaitin a non-async function: a SyntaxError (except at the top level of a module). Make the enclosing functionasync. - Async callbacks in
forEach: nothing waits; usefor...oformap+Promise.all. - Unneeded sequencing: awaiting independent work one by one.
- Assuming
asyncmakes code run in the background: it doesn't create threads. CPU-heavy synchronous work inside an async function still blocks everything (article 94); use a Worker for that. - Unhandled rejections from fire-and-forget calls:
saveDraft();withoutawaitor.catchloses its errors.
Common questions
Is async/await faster than promises?
No, it's the same mechanism. Any speed difference comes from how you structure the awaits, mainly sequential vs parallel.
Does await block the thread?
No. It suspends only the current async function; the event loop keeps running other tasks, timers and event handlers.
Can a constructor be async?
No. Constructors must return the object synchronously. Use a static async factory instead: static async create() { const obj = new Store(); await obj.init(); return obj; }.
What's the difference between return await and return in an async function?
Inside try...catch or try...finally, only return await lets the catch and finally see the promise's outcome. Elsewhere they behave the same.
Summary
asyncfunctions always return a promise:returnfulfills it,throwrejects it.awaitsuspends the async function until a promise settles, giving its value or throwing its reason; the rest of the program keeps running.- The body runs synchronously up to the first
await; code after anawaitruns as a microtask. - Handle errors with
try...catch...finally; usereturn awaitinsidetry. - Independent awaits should run together via
Promise.all; usefor...offor sequential loops andmap+Promise.allfor concurrent ones, neverforEach. - Top-level
awaitworks in ES modules.
Practice Questions
What's the output order?
async function f() {
console.log("1");
await undefined;
console.log("2");
}
f();
console.log("3");
Answer
1, 3, 2. The body runs synchronously until await; the rest runs as a microtask after the current script.
What does run() resolve to, and why?
async function run() {
try {
return fetchThatRejects();
} catch {
return "fallback";
}
}
Answer
It rejects with fetchThatRejects's error; it doesn't resolve to "fallback". Without await, the promise is returned before it settles, so the catch never sees the rejection. Write return await fetchThatRejects();.
This takes about 3 seconds when each call takes 1 second. Make it take about 1 second.
const a = await getA();
const b = await getB();
const c = await getC();
Answer
const [a, b, c] = await Promise.all([getA(), getB(), getC()]);
This only works because the three calls don't depend on each other's results.
Why does sendAll resolve before any email is sent? Fix it so it resolves after all are sent.
async function sendAll(users) {
users.forEach(async (u) => await sendEmail(u));
}
Answer
forEach ignores the promises returned by the async callback, so sendAll finishes immediately. Use one of these:
async function sendAll(users) {
await Promise.all(users.map((u) => sendEmail(u))); // concurrent
}
async function sendAllInOrder(users) {
for (const u of users) await sendEmail(u); // sequential
}
Previous: Promise.all, allSettled, race and any: Running Promises in Parallel in JavaScript
Next: Async Iteration in JavaScript: for await...of, Async Generators and Streams

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.