Async/Await
A cleaner way to write asynchronous code so it reads like normal, step-by-step code.
What is it?
Promises fixed the "callback mess", but long .then() chains can still be hard to read. async/await is syntax built on promises that lets async code look synchronous, reading top to bottom, without blocking the rest of the program.
Mark a function async. Inside it, put await before a promise to pause that function (and only that function) until the promise settles.
Explain like I'm 10
It's like a recipe written as a checklist instead of a tangle of arrows: 'wait for the water to boil, then add pasta, then wait 10 minutes.' Each step waits for the one before, in plain order.
Examples
Using async/await
async function getUserData() {
const response = await fetch("/api/user");
const data = await response.json();
return data;
}Handling errors with try/catch
async function getUserData() {
try {
const response = await fetch("/api/user");
const data = await response.json();
return data;
} catch (error) {
console.log("Failed to load user:", error);
}
}How it works
At await somePromise, JavaScript pauses that async function while the rest of the program keeps running. When the promise settles, the function resumes where it left off with the resolved value (or throws the error if it was rejected).
Why does it exist?
async/await makes promise-based code easier to read. It doesn't replace promises (it's built on them), but it removes most of the .then() boilerplate.
When to use it
Use async/await for async steps that depend on each other (fetch a user, then their orders, then show them) when you want them to read top to bottom like normal code.
When not to use it
Skip it for synchronous code that never waits; async gains you nothing there. When async tasks don't depend on each other, awaiting them one at a time is slower than starting them together with Promise.all.
Common mistakes
Forgetting the
asynckeyword on a function that usesawaitinside it.Forgetting to wrap
awaitcalls intry/catch, so rejected promises crash the function silently.Using
awaitin a loop when the calls don't depend on each other. Running them in parallel withPromise.allis faster.
Practice exercises
- Easy:
Convert a
.then()-based promise chain into anasync/awaitfunction. - Medium:
Write an async function that fetches data and handles errors with
try/catch. - Hard:
Write an async function that runs three independent async tasks in parallel using
Promise.all, instead ofawait-ing them one by one.
Interview questions
How does `async/await` relate to promises?
It's syntax sugar on top of promises. An async function always returns a promise, and await pauses that function until the given promise settles, then resumes with the value (or throws the rejection).
Does an `async` function always return a promise, even if you `return` a plain, non-promise value?
Yes. Whatever you return is wrapped in a resolved promise if it isn't one already. Callers always get a promise, never the raw value, even if the function never awaits anything.
How do you handle errors in async/await code, and how does that compare to `.catch()` on a promise chain?
Wrap the await calls in try/catch, like a synchronous throw. A rejected awaited promise becomes a thrown error at that line, so try/catch catches it just as .catch() would in a chain. Same mechanism, different syntax.
Does `await` block the entire program?
No. It only pauses the current async function. Control returns to the caller, and the rest of the program, including the browser UI, keeps running until the promise settles and the function resumes.
What does `await` actually do, mechanically, when it hits a promise?
It suspends the async function, registers a continuation on the promise (like a .then()), and returns control to the caller. When the promise settles, the rest of the function is scheduled as a microtask and picks up where it left off.
What happens if you `await` a value that isn't a promise at all, like a plain number?
It works. await treats it as already resolved, as if via Promise.resolve(). The function still yields briefly (resuming as a microtask) and then continues with that value.
What happens if you use `await` inside a function that isn't marked `async`?
It's a syntax error. await is only valid inside an async function (or at the top level of a module). Add async first.
Can you use `await` at the top level of a file, outside any function?
Yes, in an ES module. This is 'top-level await'. It lets a module do async setup before its exports are ready. The cost: any module that imports it must also wait for that await before it finishes loading.
Why is putting `await` inside a `for` loop for several independent async tasks often a performance mistake?
Each iteration waits for the previous call to finish before starting the next, so the tasks run one after another. If they're independent, start them all first and await them together (for example with Promise.all). That takes about as long as the slowest one, not the sum.
How do you run several independent async calls in parallel while still writing await-based code?
Start all the calls without awaiting each one, keep the promises, then await them together, usually with await Promise.all([...]). They all run at once instead of one after another.
Predict the output: an `async` function logs 'A', then awaits a resolved promise, then logs 'B'; right after calling that function (without awaiting it), the calling code logs 'C'.
'A', 'C', 'B'. Code before the first await runs synchronously when the function is called, so 'A' logs first. The function then suspends and the caller logs 'C'. Once the current synchronous code finishes, the function resumes and logs 'B'.
If an `async` function has no `await` inside it at all, does calling it still behave asynchronously in any way?
Yes. Its return value is still wrapped in a promise, and any .then() on it runs as a microtask, not synchronously. Callers can't rely on the result being ready when the call returns.
What happens to an error thrown inside an `async` function if there's no `try/catch` around it?
It doesn't crash the program synchronously. It becomes a rejection of the promise the function returns. The caller must handle it, with try/catch around an await or with .catch(), or it becomes an unhandled promise rejection.
Is an unhandled rejection from an async function any different, mechanically, from one that comes out of a raw `.then()` chain?
No, they're the same thing. An async function's promise rejecting with no handler is the same 'unhandled promise rejection' as any other rejected promise with no .catch() or awaiting try/catch.
Does `Array.prototype.forEach` wait for an `async` callback to finish before moving to the next item?
No. forEach ignores the promise its callback returns and fires every call back to back. All the callbacks start almost at once and finish in whatever order their work completes, not array order.
Given that `forEach` doesn't await async callbacks, how would you process an array's items one at a time, waiting for each before starting the next?
Use for...of with await inside: for (const item of items) { await process(item); }. A for loop really pauses at each await, so items are processed in order, unlike forEach.
How would you process every item in an array concurrently and collect all the results with async/await?
Call the async function on each item without awaiting, which gives an array of promises, then await them all with Promise.all, for example await Promise.all(items.map(process)). All the work starts together instead of one by one.
Inside a `try` block, is there a meaningful difference between `return await somePromise;` and `return somePromise;`?
Outside a try/catch, usually no; the caller gets the same value. Inside a try/catch, return await matters: the function waits for the promise, so a rejection is caught by that catch block. A bare return somePromise hands back the pending promise right away, so a later rejection isn't caught locally.
Debugging: a teammate wrote `items.forEach(async (item) => { await save(item); })` expecting the items to be saved one at a time, in order — what's actually happening, and how would you fix it?
forEach ignores the promise its callback returns, so all the save() calls start together, and forEach returns without waiting for any of them. Use a for...of loop with await save(item) for strict order, or Promise.all(items.map(save)) for concurrency, depending on what was intended.
Why is code written with async/await generally easier to debug with breakpoints than an equivalent `.then()` chain?
It steps like ordinary sequential code. You can set a breakpoint on any line and step over each await while local variables stay in scope. With a .then() chain you jump between separate callbacks, each with its own scope and stack frame.
Is it valid to use `await` inside a `.then()` callback? Is that a normal pattern to write?
Only if that callback is itself async. It works, but mixing the two styles in one piece of code is discouraged. Pick one style (usually async/await) for a block of logic.
If an `async` function throws before reaching its first `await`, is that throw synchronous, or does it still produce a rejected promise?
It still produces a rejected promise, not a synchronous throw that a plain try/catch around the call could catch. An async function always wraps its outcome, success or failure, in a promise, even before any await.
How would you retry a flaky async operation up to a fixed number of times using async/await?
Put the attempt in a loop with try/catch. On success, return the result. On failure, catch the error and loop again, or once the retry limit is reached, rethrow (or return a failure value).
What's the benefit of using `Promise.allSettled()` together with async/await over wrapping each individual `await` in its own `try/catch`?
Promise.allSettled() runs independent operations concurrently and reports every outcome, so one failure doesn't hide the others. Wrapping each await in its own try/catch is more verbose, and done naively in a loop it also loses the concurrency.
Predict the output: an `async` IIFE logs 'start', awaits a `setTimeout`-based promise, then logs 'end'; right after invoking it, the outer code logs 'after call'.
'start', 'after call', then 'end'. 'start' runs synchronously when the IIFE begins. The await suspends it and returns control, so 'after call' logs next. Only when the timer fires and its promise resolves does the IIFE resume and log 'end'.
Can an `async` function be combined with generator syntax, and is that something typical application code reaches for?
Yes. An async generator function (async function*) yields values over time, and the consumer reads them with for await...of. It's a specialized tool for async streams of values (like paginated API results) and much less common than a plain async function.
Why does wrapping every single `await` in the codebase in its own try/catch, versus one try/catch around several sequential awaits, matter for how precisely you can respond to failures?
One try/catch around several awaits catches a failure from any of them, but doesn't tell you which step failed unless you inspect the error. Wrapping each await (or tagging errors) lets you respond per step, like retrying just that step or using a specific fallback, instead of treating the block as all-or-nothing.
If two unrelated `await` calls are written back-to-back in an `async` function without `Promise.all`, does the second one start only after the first fully resolves, or do they overlap at all?
No overlap at all. The second call's promise isn't even created until the function resumes after the first await, so they run strictly one after the other.
What determines whether the code immediately after calling an `async` function (without awaiting the call) runs before or after the code inside that function?
Code inside the async function up to its first await runs synchronously before control returns to the caller, so it runs first. Everything after that first await is deferred, so the caller's next code usually runs before the function resumes.
Why doesn't marking a function `async` change how long its non-async internal work takes to execute?
async only changes how the result is delivered (wrapped in a promise, with pauses at await). It doesn't speed up the function's synchronous work or move it to another thread. A slow synchronous loop in an async function still blocks everything, just like in a regular function.
You need to fetch a user, then, only once you have their ID, fetch their orders. Why can't you simply start both fetches at the same time with `Promise.all`?
The second request needs the user's ID, which only exists after the first one finishes. That's a real dependency, so awaiting the first call before starting the second is correct. Promise.all only helps when the calls are truly independent.