Async JavaScript: Node.js nextTick, libuv, streams and events, Web Workers, off-main-thread work, concurrency patterns, async iteration, cancellation, timeouts, retries, async/await, combinators and the event loop – Front End interview prep
2,485 interview-style multiple-choice questions on Async JavaScript: promises, async/await and the event loop, organized by topic: concepts, scenarios, code to read and tradeoffs, each with a short explanation. Learn the 95 key terms with the flashcards first, then test yourself.
Take the practice test · Flashcards · All study tools
What it covers
- 4.1 The event loop and the call stack
- 4.2 Microtasks, timers and rendering
- 4.3 Promise basics and chaining
- 4.4 Combinators and error handling
- 4.5 async and await
- 4.6 Cancellation, timeouts and retries
- 4.7 Concurrency patterns and async iteration
- 4.8 Web Workers and off-main-thread work
- 4.9 Node.js async: nextTick, libuv, streams and events
Key terms
4.1 The event loop and the call stack
- Call stack
- The stack of active function frames
- Event loop
- The loop that runs a task, drains the microtask queue, renders if needed, and repeats
- Event-loop starvation
- Keeping the thread so busy that queued tasks, input, and rendering cannot run in time
- Execution context
- The environment for one running piece of code, including its bindings and ; function contexts are the frames of the call stack
- Frame budget
- The time available to finish work before the next display refresh, about 16.7ms at 60Hz
- INP
- Interaction to Next Paint, a Core Web Vital for responsiveness
- Long task
- Main-thread work over 50ms
- Macrotask
- A task such as a timer, I/O callback or UI event, run one per loop turn
- Main thread
- The page thread that runs ordinary JavaScript, much of the DOM, and coordinates rendering work
- Microtask
- A high-priority callback (promise reaction, queueMicrotask) run after the current task
- Run to completion
- Once a function starts on a thread, other JS on that thread waits until it returns or throws
- Task (macrotask)
- A queued unit of work such as a timer callback or event
- Task queue
- A host queue of tasks (macrotasks) the event loop pulls from when the JavaScript stack is empty
- Web Worker
- A background thread for JavaScript that communicates by messages and has no DOM
4.2 Microtasks, timers and rendering
- Forced synchronous layout
- A layout computed immediately because script read geometry after a DOM write; also called a forced reflow
- IdleDeadline
- The object passed to a requestIdleCallback callback, with timeRemaining() and didTimeout
- Layout thrashing
- Interleaved DOM writes and layout reads that force reflows
- Microtask checkpoint
- The event-loop step that drains the microtask queue until it is empty
- queueMicrotask
- An API that queues a function as a microtask, so it runs after the current JavaScript and before the next task or rendering
- requestAnimationFrame
- Callback that runs before the next repaint
- requestIdleCallback
- An API that runs a callback when the browser has idle time in a frame, with an optional timeout
- scheduler.yield
- API to yield to the main thread and continue soon after
- Timer nesting level
- HTML's count of nested timer tasks; after five levels, browsers clamp the delay to about 4ms
4.3 Promise basics and chaining
- Executor
- The function passed to new Promise; it runs immediately and receives resolve and reject
- finally
- Promise method that runs a callback on either outcome
- Promise
- An object representing a value that will be available later, or an error
- Promise chaining
- Returning values or promises from then to sequence work
- Promise reaction
- A then, catch, or finally callback queued as a microtask when the promise settles
- Promise resolution procedure
- How resolve fulfills with a non-thenable value or adopts a thenable instead of nesting it
- Promise.all
- Waits for all promises; rejects on the first rejection
- Promise.allSettled
- Waits for all promises and reports each fulfilled or rejected result
- Promise.resolve
- Static helper that lifts a value or adopts a thenable, returning an existing native promise unchanged
- promisify
- Converting a callback API into a promise-returning one
- Revealing constructor pattern
- Capturing resolve and reject from the executor so other code can settle that promise later
- Settled promise
- A promise that has already fulfilled or rejected and will not change state
- Thenable
- Any object with a then method that promises can adopt
- Unhandled rejection
- A rejected promise with no handler; a bug that browsers log and Node.js treats as fatal by default
4.4 Combinators and error handling
- Empty iterable
- A zero-length combinator input: all and allSettled fulfill with [], race stays pending, any rejects
- Error.cause
- Property that preserves the original error when you wrap it with new context
- Promise combinator
- Static helper such as all, allSettled, race, or any that settles from a group of inputs
- Promise.any
- Fulfills with the first success; rejects only if all fail
- Promise.race
- Settles like the first input to settle
- PromiseRejectionEvent
- Event type for unhandledrejection and rejectionhandled, exposing promise and reason
- Recovering catch
- A rejection handler that returns a fallback so the rest of the chain can continue fulfilled
- rejectionhandled
- Browser event fired when a handler is finally attached to a previously unhandled rejection
- unhandledrejection
- Browser event fired for rejections with no handler
4.5 async and await
- AbortController
- Creates a signal that can cancel fetch and other async operations
- async function
- A function that returns a promise and can use await
- Async generator
- async function* that yields values over time
- Async IIFE
- An immediately invoked async function expression, used so you can await where top-level await is unavailable
- AsyncFunction
- The constructor of async functions, often obtained as (async function () {}).constructor
- await
- Pauses an async function until a promise settles, then resumes with its value or throws its error
- await using
- A declaration that disposes a resource with Symbol.asyncDispose when the block exits
- Floating promise
- A promise that is neither awaited nor given a rejection handler
- Race condition
- A bug where the result depends on which async operation finishes first
- return await
- Awaiting a promise before returning so a surrounding try/catch can see its rejection
- SuppressedError
- An error that holds a dispose failure in .error and the earlier body error in .suppressed
- Top-level await
- await at the top of an ES module
4.6 Cancellation, timeouts and retries
- AbortSignal.abort
- A static helper that returns an already-aborted signal, optionally with a custom reason
- AbortSignal.any
- A helper that returns a new signal aborted when the first of several input signals aborts, adopting that input's reason
- AbortSignal.timeout
- Signal that aborts after a set time
- Exponential backoff
- Retry delays that grow by a factor each attempt
- Idempotency key
- A client-sent key that lets a server dedupe retried writes
- Retry budget
- A cap on how many attempts may be retries, often as a share of recent traffic, so retries cannot amplify an outage
- Retry jitter
- Random variation added to retry delays so many clients do not retry in lockstep
- throwIfAborted
- An AbortSignal method that throws the abort reason if the signal has already been aborted, and otherwise returns
- TimeoutError
- The DOMException name used when an AbortSignal.timeout deadline fires, distinct from a manual AbortError
4.7 Concurrency patterns and async iteration
- Array.fromAsync
- A helper that consumes an async iterable and returns a promise for an array of the collected values
- Async iteration
- Consuming values over time with for await
- Async mutex
- A lock that lets one async critical section run at a time, so awaits cannot interleave updates to the same state
- Backpressure
- A consumer signaling a producer to slow down so a pipeline does not buffer without bound
- Concurrency pool
- A fixed number of slots that take the next task when one finishes, keeping at most N operations in flight
- In-flight dedupe
- Caching a pending promise by key so concurrent callers share one request instead of starting duplicates
- Optimistic UI
- Showing the expected result before the server confirms
- Semaphore
- Counter limiting how many operations run at once
- Web Locks API
- navigator.locks.request coordinates exclusive or shared locks across tabs and workers of one origin
4.8 Web Workers and off-main-thread work
- Atomics
- A built-in object for atomic reads, writes, waits, and notifies on SharedArrayBuffer-backed typed arrays
- Cross-origin isolation
- A browsing-context state, typically enabled by COOP and COEP headers, that allows SharedArrayBuffer and other privileged APIs
- importScripts
- A synchronous classic-worker API that loads and runs additional scripts in the worker's global scope
- OffscreenCanvas
- A canvas that can be created or transferred to a worker so drawing does not occupy the page's main thread
- Service Worker
- Event-driven proxy between the page and network
- SharedArrayBuffer
- Memory shared between threads
- SharedWorker
- A worker that same-origin tabs or iframes can share through MessagePort connections
- Structured clone
- The algorithm postMessage and structuredClone use to copy values across realms, including cycles, Maps, and Dates, but not functions or DOM nodes
- Transferable
- Object whose ownership moves between threads without copying
4.9 Node.js async: nextTick, libuv, streams and events
- AsyncLocalStorage
- Node API for per-request context across async calls
- Check phase
- Node event-loop phase where setImmediate callbacks run
- drain
- Event a writable emits when its buffer falls below highWaterMark and it is safe to write again
- EventEmitter
- Node's publish/subscribe class; emit is synchronous and an unhandled "error" event throws
- highWaterMark
- Stream buffer threshold that triggers backpressure when a writable's write returns false or a readable stops pushing
- libuv
- C library that provides Node's event loop, async I/O, and the default thread pool
- nextTick queue
- Node queue that runs before promise microtasks in CommonJS
- pipeline
- stream.pipeline or stream.promises.pipeline, which forwards errors, destroys streams, and applies backpressure
- setImmediate
- Schedules a callback in the check phase, after poll
- Zalgo
- Inconsistent sync/async callback behavior
Sample practice questions
What does this log? ```js console.log("A"); setTimeout(() => console.log("B"), 0); Promise.resolve().then(() => console.log("C")); console.log("D"); ```
- `A C D B`
- `A D B C`
- `A D C B`
- `A B C D`
Answer: C. `A D C B` Synchronous code runs first, then the microtask queue (promise callbacks), then the next macrotask (the timer).
Which of these queues a microtask?
- `queueMicrotask(fn)` and promise `.then` callbacks
- `setTimeout(fn, 0)` and `setInterval(fn, 0)`
- `addEventListener("click", fn)` and `onload`
- `requestAnimationFrame(fn)` and `requestIdleCallback`
Answer: A. `queueMicrotask(fn)` and promise `.then` callbacks Timers and events are tasks (macrotasks); promise reactions and `queueMicrotask` are microtasks.
What are the three states of a promise?
- Waiting, running and done
- Open, resolved and closed
- Started, paused and stopped
- Pending, fulfilled and rejected
Answer: D. Pending, fulfilled and rejected Once fulfilled or rejected (settled), a promise never changes state again.
What does this log? ```js Promise.resolve(1) .then(x => x + 1) .then(x => { throw new Error("bad " + x); }) .then(x => console.log("then", x)) .catch(e => console.log("catch", e.message)); ```
- `catch bad 2`
- `then 2`
- Nothing; the error is unhandled
- `catch bad 1`
Answer: A. `catch bad 2` The throw rejects the chain, skipping the next `then` and landing in `catch`.
What does an `async` function always return?
- A promise
- The value after `return`, unwrapped
- `undefined`
- A generator
Answer: A. A promise Returned values are wrapped in a fulfilled promise; thrown errors become a rejected one.
How do you cancel an in-flight `fetch` request?
- Throw an error inside the first `.then` callback
- Pass an `AbortController` signal, then call `abort()`
- Call `fetch.cancel()` on the returned promise
- Set the promise variable to `null` to release it
Answer: B. Pass an `AbortController` signal, then call `abort()` Aborting rejects the fetch with an `AbortError`; `AbortSignal.timeout(ms)` gives a built-in timeout.
What is the problem with this code if the two requests don't depend on each other? ```js const user = await getUser(id); const posts = await getPosts(id); ```
- `await` can't be used twice in one function
- They run one after the other instead of in parallel
- It leaks memory by holding both responses
- The second `await` runs before the first one
Answer: B. They run one after the other instead of in parallel Sequential awaits add the latencies together. Start both, then `await Promise.all([...])`, so the total is only as long as the slowest.
Where does code run when you create a Web Worker?
- In a hidden iframe with full DOM access
- On a separate thread, with no DOM access
- On the main thread, but at a lower priority
- On the GPU, alongside the compositor
Answer: B. On a separate thread, with no DOM access A worker has its own event loop and talks to the page with `postMessage`.
In what order does this Node.js script print? ```js setImmediate(() => console.log("immediate")); process.nextTick(() => console.log("tick")); Promise.resolve().then(() => console.log("promise")); ```
- `immediate`, `tick`, `promise`
- `tick`, `promise`, `immediate`
- `tick`, `immediate`, `promise`
- `promise`, `tick`, `immediate`
Answer: B. `tick`, `promise`, `immediate` In CommonJS, the nextTick queue drains before promise microtasks; both run before the check phase.
What runs between two macrotasks, such as two `setTimeout` callbacks?
- Garbage collection only
- Nothing; macrotasks always run back to back
- Only `requestAnimationFrame` callbacks
- All queued microtasks, then possibly a render
Answer: D. All queued microtasks, then possibly a render After each task the engine drains the microtask queue completely before the next task or rendering.
More Front End
- HTML semantics & accessibility
- CSS: box model, Flexbox, Grid
- JavaScript fundamentals
- TypeScript
- React: components, hooks & rendering
- State management: Redux, Zustand, context
- Angular and Vue basics
- Browser internals & rendering
- Web performance
- Build tools & bundlers
- Front-end testing
- Front-end security
- Mobile & cross-platform