Interview Q&A · JavaScript · 16 questions in this topic
Event Loop, Promises & Async/Await — JavaScript Interview Q&A
The async core — queues, promise machinery, parallel patterns and cancellation. Part of Async JavaScript · 204 questions in the JavaScript bank.
How does the event loop work (stack, queues, render)?
Answer
The stack runs one frame at a time; async completions queue as microtasks (promises, queueMicrotask — drained fully after each task) or macrotasks (timers, I/O, events — one per turn); rendering typically slots between macrotasks. Starving microtasks (promise loops) freeze rendering — the loop has no preemption.
Stack-empty → microtasks-all → one-macrotask → render is the turn anatomy.
Key points
- 1Stack — synchronous execution.
- 2Microtasks — promises, drained fully.
- 3Macrotasks — timers/I/O, one per turn.
Example
setTimeout(() => console.log('t'), 0); // macrotask Promise.resolve().then(() => console.log('p')); // microtask: first
💡 Microtasks-before-macrotasks explains every ordering puzzle.
What is a Promise (states, executor, then/catch)?
Answer
A promise is a future-value placeholder: pending → fulfilled/rejected (settled once, immutable after). The executor runs immediately (sync!) with resolve/reject; then/catch/finally register reactions returning new promises (chainable). Unhandled rejections crash modern runtimes — always terminate chains with catch.
Executor-sync, settlement-once, chains-composed is the model.
Example
const p = new Promise((resolve) => { // executor runs NOW (synchronously) resolve(42); }); p.then((v) => v * 2).then(console.log); // 42, then 84
How does promise chaining work (returning values vs promises)?
Answer
then returns a new promise: returning a value fulfills it (assimilation), returning a promise adopts its fate (flattening — no nested promise pyramids), throwing rejects it. Forgetting return passes undefined downstream — the silent chain-breaker.
Return-or-adopt is the chaining law; missing-return is the bug.
Example
fetchUser(id) .then((u) => fetchOrders(u.id)) // returned promise adopted .then((orders) => render(orders)) .catch(showError); // any step's failure lands here
How do `Promise.all`, `allSettled`, `race` and `any` differ?
Answer
all: all fulfill in order or first-reject wins (fail-fast batch). allSettled: waits for all, reporting status/value/reason per input (bulk jobs). race: first settles wins (timeouts). any: first fulfills wins, rejects only if all reject (AggregateError).
Fail-fast → all; complete-picture → allSettled; timeout → race; first-success → any.
Key points
- 1all — ordered results or first rejection.
- 2allSettled — every outcome reported.
- 3race — first settlement; any — first fulfillment.
Example
const withTimeout = (p, ms) => Promise.race([ p, new Promise((_, rej) => setTimeout(() => rej(new Error('timeout')), ms)), ]);
💡 Timeout-via-race is the pattern to have ready.
How does `async/await` work (and what does it desugar to)?
Answer
async marks functions returning promises; await pauses that function (not the thread) until settlement, unwrapping values or throwing rejections into try/catch. Desugared: generator-plus-promise state machines. Sequential awaits serialize (slow); independent awaits parallelize via Promise.all.
Pause-function-not-thread is the mental model; parallelize-independent is the performance rule.
Example
async function load(id) { try { const user = await fetchUser(id); // pauses here only return user; } catch (e) { /* rejection lands here */ } }
How do you handle errors in async code (try/catch vs .catch)?
Answer
async/await: try/catch around awaits (rejections throw). Chains: terminal .catch (plus rethrow-or-handle discipline). Parallel: allSettled for partial failure, all for fail-fast. Top-level: unhandledrejection hooks plus process handlers as backstops, never primary logic.
Await-throws-into-try is the async/await rule.
Example
async function safe(id) { try { return await fetchUser(id); } catch (e) { log(e); return fallbackUser(); } }
Why does `await` in a loop serialize (and how do you fix it)?
Answer
await inside for...of pauses per iteration — N sequential round trips. Fix: map to promises then await Promise.all (one concurrent batch), or bounded pools (p-limit) for huge N. Order preserved with all; completion-order needs allSettled/race plumbing.
Map-then-all is the parallel-loop idiom.
Example
// slow: sequential // for (const id of ids) await fetchOne(id); // fast: concurrent batch const rows = await Promise.all(ids.map(fetchOne));
💡 Serial-vs-batch latency math (N×RTT vs 1×RTT) is the point to quantify.
How do you cancel async work (AbortController)?
Answer
AbortController signals (fetch, streams, custom listeners) cooperatively — abort() rejects listeners with AbortError; operations must observe the signal. Timeouts, navigation-away, and superseded requests (search-as-you-type) are the canonical uses.
Cooperative-not-preemptive: code must listen for the signal.
Example
const c = new AbortController(); fetch(url, { signal: c.signal }); // pass signal in // c.abort(); // rejects with AbortError
💡 Signal-passing plus AbortError-catching is the cancellation pair.
What are microtasks vs macrotasks (ordering puzzles)?
Answer
Microtasks (promise reactions, queueMicrotask, MutationObserver) drain completely after each macrotask before rendering/next task. Macrotasks (setTimeout, I/O, events, rAF) yield one per turn. Nested microtasks can starve the loop — queue depth matters.
a-d-c-b ordering puzzles all reduce to this drain rule.
Example
console.log('a'); setTimeout(() => console.log('b'), 0); Promise.resolve().then(() => console.log('c')); console.log('d'); // a d c b
How do `fetch`, response handling and errors work?
Answer
fetch returns promises resolving to Response (check response.ok — HTTP errors do NOT reject; only network failures do). Parse via .json()/.text() (async), handle aborts (AbortError) and timeouts (race wrapper). Retries need idempotency awareness (GET-safe, POST-careful).
ok-check-plus-network-only-rejection is the fetch contract.
Example
const r = await fetch(url, { signal }); if (!r.ok) throw new Error(`HTTP ${r.status}`); const data = await r.json();
How do generators (`function*`, `yield`) relate to async?
Answer
Generators pause/resume via yield (manual iteration protocol) — the historical async foundation (co-style runners) before async/await desugared the pattern natively. Modern uses: lazy sequences, custom iterables, and delegation (yield*).
Async/await is generators-plus-promises made native.
Example
function* seq() { yield 1; yield 2; } const it = seq(); it.next(); // { value: 1, done: false }
What is the difference between parallel, concurrent and sequential async?
Answer
Sequential: awaits in order (latency sums). Concurrent (JS single-threaded): overlapping waits via Promise.all (latency maxes). Parallel: true multi-thread via workers (CPU-bound scale). I/O-bound wants concurrent; CPU-bound wants workers.
Concurrency-overlaps-waits, parallelism-uses-cores is the split.
Key points
- 1Sequential — ordered, latency sums.
- 2Concurrent — overlapped waits, one thread.
- 3Parallel — workers, multiple cores.
How do you limit concurrency (pool pattern)?
Answer
Worker-pool: N slots consume a task queue (p-limit style), preserving backpressure — unbounded Promise.all on 10k inputs exhausts sockets/memory. Results ordered by index; errors collected per allSettled semantics.
Unbounded-all is the load-incident shape; pools are the production answer.
Example
// p-limit sketch: run at most N at once // const limit = pLimit(5); // await Promise.all(urls.map((u) => limit(() => fetchOne(u))));
💡 Backpressure-by-design is the pool value proposition.
How do you retry with backoff (and when do you stop)?
Answer
Retry transient failures (network, 429/5xx) with exponential backoff plus jitter (thundering-herd defense), capped attempts, and idempotency keys for unsafe methods. Never retry non-idempotent POSTs blindly or 4xx client errors.
Backoff-plus-jitter-plus-cap is the retry triple.
Example
// delay = min(cap, base * 2 ** attempt) + jitter💡 Jitter-defeats-herds is the detail that shows production experience.
What are top-level await and async IIFE patterns?
Answer
Top-level await (modules) pauses module evaluation for dependencies — sequential, initialization-friendly. Async IIFEs wrap awaits where top-level is unavailable (scripts, older setups, conditional flows).
Module-graph blocking is the top-level cost to respect — keep it for true init dependencies.
Example
// module top-level: // const config = await loadConfig(); // classic fallback: // (async () => { await init(); })();
How do `setTimeout`, `setInterval` and `requestAnimationFrame` differ?
Answer
setTimeout runs once after delay (clamped/nested-throttled). setInterval repeats (drift-prone; recursive setTimeout self-corrects). requestAnimationFrame fires pre-paint (~60fps, paused offscreen) for visual work.
Visual → rAF; once-later → timeout; repeating → interval-or-recursive-timeout.
Key points
- 1setTimeout — once, delayed.
- 2setInterval — repeating, drifts.
- 3rAF — pre-paint, visual only.
Example
// self-correcting repeat: // const tick = () => { work(); setTimeout(tick, 1000); };
💡 Recursive-timeout-beats-interval is the drift fix.
Recommended resourcesAffiliate links · may earn us a commission