Question presented to candidate: "You see 'async' in front of a function and 'await' inside it. What does the JavaScript engine actually do with those keywords, and does await block the whole program?"
What a strong answer should cover:
- An
asyncfunction always returns a Promise — even a plainreturn 42inside one becomes a Promise that resolves to42, and a thrown error becomes a rejected Promise, verifiably, not just by convention. awaitpauses execution only within that async function — it does not block the thread, the event loop, or any other concurrently running code. Control returns to the event loop while the awaited Promise settles, and other work (other requests, timers, other async functions) proceeds normally in the meantime.async/awaitis syntax over Promises, not a separate mechanism — this is whytry/catchworks around anawait: a rejected Promise being awaited is exactly equivalent to a thrown error at that point in the function.- The main practical benefit is readability: sequential async logic reads top-to-bottom like synchronous code, with ordinary control flow (
if, loops,try/catch) working exactly as it does in synchronous code — no.then()nesting or chaining gymnastics required. - The most common real bug is writing sequential
awaits for operations that do not actually depend on each other, silently serializing work that could run concurrently viaPromise.all— this is a behavior/performance bug, not a syntax error, so it does not surface as an obvious mistake. for await...ofextends the same idea to async iterables (including Node streams) — pulling the next value only once the previous iteration's work, including anyawaitinside the loop body, actually finishes; this interacts directly with stream backpressure, covered in its own dedicated question.
Clarifying questions expected:
- "Are these steps sequential-by-dependency, or just written sequentially out of habit?" — decides whether
Promise.allshould replace some of theawaits. - "Does the interviewer want proof that
awaitdoes not block other code, or just the syntax explained?" — these call for different depths of answer.
Code / implementation expected: Yes — showing an async function's return value actually being a Promise, and a thrown error becoming a rejection caught by an ordinary try/catch, is the concrete, verifiable core of the answer.