async / await — JavaScript interview guide
async / await
async/await is cleaner syntax over promises. An async function always returns a promise, and await pauses that function (not the whole page) until a promise settles.
See it run
Press Play, or step with Next. Watch the highlighted line, the Call Stack and memory change together.
What "await" really does
1async function getUser() {2console.log("A");3const user = await fetchUser();4console.log("C", user);5}6▶getUser();8console.log("B");
| user | <uninitialized> |
empty
Waits until the Call Stack is empty. Microtasks always go first.
empty
empty
nothing printed yet
What happens:getUser() is called and pushed onto the stack. An async function runs synchronously until its first await.
Tip: click the box and use ← → keys to step, space to play.
Explained simply
Error handling
Use try/catch around awaits, just like synchronous code.
async function loadUser(id) {
try {
const res = await fetch("/api/users/" + id);
if (!res.ok) throw new Error("HTTP " + res.status);
return await res.json();
} catch (err) {
console.error(err);
return null;
}
}Sequential vs parallel
Awaiting one after another is slow when requests do not depend on each other. Start them together with Promise.all.
// slow: ~2s
const a = await getA(); // 1s
const b = await getB(); // 1s
// fast: ~1s
const [a2, b2] = await Promise.all([getA(), getB()]);Remember this
- await only pauses the async function it is in.
- Code after await runs later as a microtask.
- forEach does not wait for async callbacks — use for...of or Promise.all with map.
Interview questions
What does an async function return?
Always a promise. A returned value becomes the fulfilled value; a thrown error becomes a rejection.
Why does await inside forEach not work as expected?
forEach ignores the promises returned by the callback, so it does not wait. Use for...of for sequence or Promise.all(arr.map(...)) for parallel.
Practice
- Fetch 3 users in parallel and show them in order.
- Write retry(fn, times) with async/await.