Asynchronous JavaScript Interview Questions: 10 Questions with Clear Answers
Asynchronous JavaScript is a core pillar of front-end technical screenings and live-coding rounds for developers with 0–5 years of experience. Beyond knowing basic async/await syntax, interviewers evaluate whether you understand Promise settlement semantics, error propagation, request cancellation, microtask scheduling, and how to prevent race conditions in real-world UIs.
This guide covers 10 high-frequency asynchronous JavaScript interview questions with concise spoken answers, detailed explanations, code examples, common mistakes, and likely follow-up questions.
Question Index
| # | Question Focus | Key Concept | Difficulty |
|---|---|---|---|
| 1 | Promise Combinators | all vs. allSettled vs. race vs. any | Junior-Mid |
| 2 | fetch() Error Semantics | Network failure vs. HTTP response.ok | Junior |
| 3 | async/await in Array Loops | forEach pitfall vs. Promise.all / for...of | Junior-Mid |
| 4 | return await in try/catch | Rejection interception vs. pass-through | Mid-Senior |
| 5 | AbortController & AbortSignal | Canceling fetch() & AbortSignal.timeout() | Mid |
| 6 | queueMicrotask() vs. setTimeout | Microtask checkpoint vs. macrotask queue | Mid |
| 7 | Unhandled Promise Rejections | unhandledrejection & detached chains | Mid |
| 8 | Sequential vs. Parallel await | Request waterfalls & concurrency control | Mid-Senior |
| 9 | Async Iteration (for await...of) | Streaming chunks & paginated cursors | Mid-Senior |
| 10 | UI Race Conditions | Stale-response guards & cancellation | Senior |
Q1. How do Promise.all(), Promise.allSettled(), Promise.race(), and Promise.any() differ?
Level: Junior-Mid
What the interviewer is checking: Knowing each combinator's short-circuiting rule and what it resolves or rejects with.
Short answer to say out loud
"Promise.all() fails fast on the first rejection. Promise.allSettled() waits for every promise to settle and returns an array of status objects. Promise.race() settles with the very first promise to fulfill or reject, while Promise.any() resolves with the first fulfillment and only rejects with an AggregateError if all promises reject."
Detailed explanation
Promise.all(iterable): Fulfills when every input promise fulfills; rejects immediately with the first rejection reason.Promise.allSettled(iterable): Never rejects on input rejections; returns{ status: 'fulfilled', value }or{ status: 'rejected', reason }for each item.Promise.race(iterable): Adopts the outcome (fulfilled or rejected) of the first settled promise.Promise.any(iterable): Ignores rejections until one promise fulfills; rejects withAggregateErroronly if every input rejects.
Example
const p1 = Promise.reject(new Error('Service A down'));
const p2 = Promise.resolve('Service B OK');
const settled = await Promise.allSettled([p1, p2]);
// [{ status: 'rejected', reason: Error }, { status: 'fulfilled', value: 'Service B OK' }]
const fastestSuccess = await Promise.any([p1, p2]);
// 'Service B OK'
Common mistakes
- Using
Promise.all()for independent dashboard widgets where one failure blanks the entire screen. - Passing an empty array
[]toPromise.race([]), which stays pending forever.
Likely follow-up questions
- "What does
Promise.all([])resolve to, and what doesPromise.any([])reject with?" - "Does
Promise.race()cancel the losing promises automatically?"
Q2. Why does fetch() not reject on HTTP 404 or 500 responses?
Level: Junior
What the interviewer is checking: Distinguishing transport/network failures from valid HTTP responses with error status codes.
Short answer to say out loud
"fetch() only rejects when the request fails at the network layer or is aborted—for example, offline DNS failure or a CORS block. An HTTP 404 or 500 is still a valid HTTP response from the server, so fetch() resolves and you must check response.ok explicitly."
Detailed explanation
In the Fetch specification, receiving HTTP headers—even with a 404 Not Found or 500 Internal Server Error status—means the HTTP transaction completed. response.ok is a boolean that is true only for status codes in the 200–299 range.
Example
async function getUser(id) {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) {
throw new Error(`HTTP ${res.status}: ${res.statusText}`);
}
return res.json();
}
Common mistakes
- Calling
await res.json()before checkingres.ok, which throws a confusingSyntaxErrorif the 500 page returned HTML. - Assuming
try/catcharoundfetch()automatically catches 401 or 404 responses.
Likely follow-up questions
- "Why can you only read
res.json()orres.text()once on aResponseobject?" - "How does
res.clone()work if you need to inspect a response body twice?"
Q3. Why does async/await inside Array.prototype.forEach() behave unexpectedly?
Level: Junior-Mid
What the interviewer is checking: Understanding that forEach ignores returned Promises and does not await callbacks.
Short answer to say out loud
"forEach invokes its callback synchronously for every element and discards the returned Promise. Code right after forEach runs immediately before any await inside the callback finishes. Use Promise.all(items.map(...)) for parallel execution or for...of for sequential execution."
Detailed explanation
Array.prototype.forEach has no await inside its internal loop. Passing an async callback fires all async operations concurrently without returning a Promise you can await, making completion order unpredictable and errors easy to miss.
Example
// Buggy: logs 'Done' before any saveUser finishes
items.forEach(async (item) => {
await saveItem(item);
});
console.log('Done');
// Fixed (parallel):
await Promise.all(items.map((item) => saveItem(item)));
// Fixed (sequential):
for (const item of items) {
await saveItem(item);
}
Common mistakes
- Using
Array.prototype.map(async ...)and forgetting to wrap the resulting array of Promises inPromise.all(). - Using
for...ofwithawaitwhen tasks are completely independent and could run in parallel.
Likely follow-up questions
- "What happens if you pass an
asynccallback toArray.prototype.filter()?" - "How would you run
items.map()with a maximum concurrency of 3?"
Q4. When does return await inside a try/catch block actually matter?
Level: Mid-Senior
What the interviewer is checking: Understanding Promise unwrapping vs. local exception catching in async functions.
Short answer to say out loud
"Outside try/catch, return promise and return await promise behave almost identically (aside from stack-trace detail). Inside try/catch, however, return promise hands the still-pending Promise directly to the caller, bypassing the local catch block if it rejects. return await promise settles it first so catch can handle rejections."
Detailed explanation
When an async function executes return someAsyncCall(), the function exits the try block immediately and resolves its outer Promise to someAsyncCall(). Any subsequent rejection happens after the try/catch scope has already exited. Adding await pauses execution inside try until settlement.
Example
async function fetchSafe(url) {
try {
// Without `await`, a rejection skips `catch`!
return await fetch(url).then((r) => r.json());
} catch (err) {
console.error('Caught locally:', err);
return null;
}
}
Common mistakes
- Removing
awaitinsidetry/catchbecause of a lint rule (no-return-awaitwithoutin-try-catchawareness). - Assuming
finallyruns before a returned unawaited Promise settles—finallyruns synchronously whentryreturns unlessreturn awaitis used.
Likely follow-up questions
- "How does
return awaitaffect async stack traces in modern V8?" - "What happens in a
finallyblock if youreturnwithoutawaitinsidetry?"
Q5. How does AbortController cancel fetch() requests, and what are AbortSignal.timeout() and AbortSignal.any()?
Level: Mid
What the interviewer is checking: Practical knowledge of modern request cancellation and signal composition.
Short answer to say out loud
"AbortController creates a controller and an AbortSignal passed to fetch(..., { signal }). Calling controller.abort() rejects the fetch() Promise with an AbortError (or custom reason) and closes the underlying connection. AbortSignal.timeout(ms) creates a self-aborting signal, and AbortSignal.any([...]) combines multiple signals."
Detailed explanation
Passing signal into fetch() or addEventListener() lets you tear down in-flight network requests and event listeners cleanly. When aborted, fetch() rejects with a DOMException named 'AbortError' (unless a custom reason is passed to controller.abort(reason)), which you should ignore in error UIs so canceled requests do not flash error banners.
Example
const userController = new AbortController();
const signal = AbortSignal.any([
userController.signal,
AbortSignal.timeout(5000),
]);
try {
const res = await fetch('/api/report', { signal });
return await res.json();
} catch (err) {
if (err.name === 'AbortError' || err.name === 'TimeoutError') return null;
throw err;
}
Common mistakes
- Reusing a single
AbortControllerafter.abort()has been called—an aborted signal stays aborted permanently. - Treating
AbortErroras a real network failure and showing a "Something went wrong" toast to the user.
Likely follow-up questions
- "What is the difference between
AbortErrorandTimeoutErrorwhen usingAbortSignal.timeout()?" - "How else can an
AbortSignalbe used besidesfetch()?"
Q6. What is the difference between queueMicrotask() and setTimeout(fn, 0)?
Level: Mid
What the interviewer is checking: Understanding the browser event loop's microtask checkpoint vs. task (macrotask) queue and render timing.
Short answer to say out loud
"queueMicrotask() schedules a callback in the microtask queue, which drains completely right after the current synchronous call stack empties and before the browser paints or runs the next macrotask. setTimeout(fn, 0) schedules a macrotask, allowing pending microtasks—and potentially a browser render frame—to run first."
Detailed explanation
After every task finishes, the JavaScript runtime drains all pending microtasks (Promise .then/.catch/.finally continuations and queueMicrotask callbacks), including any new microtasks queued during that drain. Only after the microtask queue is empty can the event loop proceed to rendering or the next macrotask (setTimeout, UI events).
Example
setTimeout(() => console.log('1: macrotask'), 0);
queueMicrotask(() => console.log('2: microtask'));
console.log('3: sync');
// Output order: '3: sync', '2: microtask', '1: macrotask'
Common mistakes
- Recursively calling
queueMicrotask()infinitely, which starves the main thread and freezes UI rendering. - Expecting
setTimeout(fn, 0)to execute in literally 0 ms (browsers clamp nested timers to ~4 ms).
Likely follow-up questions
- "When is
queueMicrotask()preferable toPromise.resolve().then()?" - "How does
requestAnimationFramefit relative to microtasks andsetTimeout?"
Q7. How do unhandled Promise rejections happen, and how should you avoid them?
Level: Mid
What the interviewer is checking: Understanding Promise rejection tracking, detached chains, and global unhandledrejection handlers.
Short answer to say out loud
"An unhandled rejection occurs whenever a Promise rejects and no .catch() handler or try/catch around await is attached before the end of the current microtask turn. In browsers this fires the unhandledrejection event on window, and in Node.js it can terminate the process."
Detailed explanation
A common source of unhandled rejections is creating a Promise (e.g., const p = fetchData()) and awaiting something else first before attaching await p. If p rejects while you are awaiting another operation, the runtime flags it as unhandled during that turn even if you intend to await p later.
Example
// Risky: if fetchA rejects while awaiting fetchB, unhandledrejection fires!
const aPromise = fetchA();
const b = await fetchB();
const a = await aPromise;
// Safe: attach combinator or catch immediately
const [aRes, bRes] = await Promise.all([fetchA(), fetchB()]);
Common mistakes
- Forgetting
returninside a.then()chain, creating a detached Promise whose rejection is never observed by the outer.catch(). - Attaching
.catch()asynchronously inside asetTimeoutinstead of synchronously in the same turn.
Likely follow-up questions
- "What is the
rejectionhandledevent onwindow?" - "Why is global
window.addEventListener('unhandledrejection', ...)useful for front-end observability?"
Q8. How do you eliminate await waterfalls without overwhelming the browser or API?
Level: Mid-Senior
What the interviewer is checking: Spotting accidental sequential await calls and knowing how to batch or limit concurrency.
Short answer to say out loud
"Independent await statements written one after another create a network waterfall where total latency is the sum of all requests. Start independent Promises concurrently and join them with Promise.all(), or use a bounded concurrency worker pool when processing large lists."
Detailed explanation
If three independent API calls each take 200 ms, awaiting them sequentially takes ~600 ms. Starting them together with Promise.all() cuts total time to ~200 ms. However, firing 500 fetch() calls at once via Promise.all() can hit browser per-origin limits or rate-limit the API, so batching or a worker-pool pattern keeps throughput controlled.
Example
// Waterfall (~600ms):
const user = await fetchUser(id);
const posts = await fetchPosts(id);
// Concurrent (~200ms):
const [user, posts] = await Promise.all([fetchUser(id), fetchPosts(id)]);
Common mistakes
- Wrapping dependent calls in
Promise.all()when the second call needs an ID from the first. - Firing unbounded
Promise.all(ids.map(fetchItem))on thousands of items.
Likely follow-up questions
- "How do HTTP/2 and HTTP/3 multiplexing change browser connection limits?"
- "How would you implement a simple concurrency-limited queue in 15 lines of JavaScript?"
Q9. How does for await...of work, and when is it useful on the front end?
Level: Mid-Senior
What the interviewer is checking: Familiarity with async iterables (Symbol.asyncIterator) for streaming responses or paginated APIs.
Short answer to say out loud
"for await...of iterates over an async iterable—an object implementing [Symbol.asyncIterator]() whose .next() returns a Promise for { value, done }. On the front end, it is ideal for reading fetch() ReadableStream chunks or lazily consuming cursor-paginated API endpoints."
Detailed explanation
Unlike Promise.all(), which waits for everything before returning, for await...of processes each resolved chunk or page as it arrives, keeping memory usage low and allowing incremental UI updates (such as streaming LLM responses).
Example
async function* fetchPages(startUrl) {
let url = startUrl;
while (url) {
const res = await fetch(url);
const data = await res.json();
yield data.items;
url = data.nextUrl;
}
}
for await (const pageItems of fetchPages('/api/logs?cursor=0')) {
renderItems(pageItems);
}
Common mistakes
- Breaking out of
for await...ofearly without realizing it triggers.return()on the async iterator for cleanup. - Using
for await...ofon an array of Promises expecting parallel resolution—it awaits them in array order, not settlement order.
Likely follow-up questions
- "What is the difference between
ReadableStreamwithgetReader()andfor await...of?" - "How do you cancel an async generator cleanly if the user navigates away?"
Q10. How do you prevent stale-response race conditions in UI components?
Level: Senior
What the interviewer is checking: Solving out-of-order async resolution bugs in search inputs, tabs, or filters.
Short answer to say out loud
"If request A is slower than request B, A can resolve later and overwrite B's newer UI state. Prevent this by canceling the previous request with AbortController on cleanup, or by tracking a monotonic request ID / boolean ignore flag inside the effect so stale completions are discarded."
Detailed explanation
Even when AbortController cancels fetch(), you may wrap non-cancelable async work (like IndexedDB or third-party SDK calls). Combining AbortController with an ignore boolean (or incrementing requestIdRef) guarantees that only the latest active invocation commits state.
Example
let latestRequestId = 0;
async function handleSearch(query) {
const currentId = ++latestRequestId;
const results = await searchApi(query);
if (currentId !== latestRequestId) return; // Discard stale response
renderResults(results);
}
Common mistakes
- Assuming faster network requests always finish in the order they were sent.
- Relying on debouncing alone—debouncing reduces request frequency, but two slow/fast requests can still cross in flight.
Likely follow-up questions
- "Why does React's
useEffectdocumentation recommend anignoreflag pattern alongsideAbortController?" - "How do libraries like TanStack Query deduplicate and cancel stale queries automatically?"
Preparation Checklist
- Know all 4 Promise combinators: Rehearse exact settlement rules for
all,allSettled,race, andany. - Check
response.ok: Never assumefetch()rejects on HTTP 4xx/5xx status codes. - Avoid
forEachwithasync: Default toPromise.all(arr.map(...))for parallel work andfor...offor sequential steps. - Cancel in-flight work: Practise wiring
AbortControllerandAbortSignal.timeout()intofetch()calls. - Guard against race conditions: Always pair async UI updates with cancellation or a monotonic request-ID check.
Conclusion
Mastering asynchronous JavaScript goes far beyond writing async and await. When you articulate Promise combinator trade-offs, fetch() error boundaries, microtask ordering, AbortController cancellation, and race-condition guards, you demonstrate the reliability expected in production front-end engineering.