JavaScript · Async JavaScript · Junior · Concept
How does `async/await` work under the hood?
Short Interview Answer
An `async` function always returns a Promise; `await` pauses the function's progress until the awaited promise settles, then resumes with the value or throws.
Detailed Explanation
`async function` wraps the return value in a resolved promise (or rejects if you throw). `await` desugars roughly to promise `.then` continuation of the rest of the function (similar to a state machine). While awaiting, the call stack unwinds so the event loop can run other work. Errors from awaited rejections become throw-able in try/catch. `await` on non-promises wraps them via `Promise.resolve`. Top-level await exists in modules. Avoid awaiting in serial loops when parallelism is safe.
Example
async function getJson(url) {
const res = await fetch(url);
if (!res.ok) throw new Error(String(res.status));
return res.json();
}Interview Tip
State 'async functions always return promises' clearly.
Common Mistake
Forgetting to `await` or return a promise inside `async`, causing race bugs.