JavaScript Asynchronous Programming

1 min read

Asynchronous programming in JavaScript enables non-blocking execution, allowing long-running operations such as network requests, file reading, or timers to run in the background without freezing the main thread. Because JavaScript is single-threaded, concurrency is managed via the Event Loop, which orchestrates execution between the call stack, macrotask queue, and microtask queue (handling promises). Over time, JS concurrency evolved from nested callback functions (“callback hell”) to cleaner ES6 Promises and modern syntactic sugar like async/await. Mastering how microtasks execute ahead of macrotasks, how to handle asynchronous error boundaries, and how non-blocking APIs operate is essential for building scalable web applications and passing technical engineering interviews.

1. What is the primary characteristic of JavaScript's execution model?

a) Multi-threaded with preemptive task scheduling
b) Single-threaded, non-blocking, asynchronous, and concurrent via an event loop
c) Multi-process with shared memory architecture
d) Synchronous and blocking by default
Correct Answer: b) Single-threaded, non-blocking, asynchronous, and concurrent via an event loop
Explanation:
JavaScript executes code on a single main thread but achieves concurrency and non-blocking I/O using web APIs and the event loop.

2. Which component in the JavaScript runtime environment is responsible for executing code, managing function invocation, and keeping track of execution contexts?

a) The Call Stack
b) The Task Queue
c) The Microtask Queue
d) The Heap
Correct Answer: a) The Call Stack
Explanation:
The call stack is a LIFO (Last In, First Out) data structure that records execution contexts.

3. Where are asynchronous callback functions placed when their corresponding Web API or timer operations complete?

a) Directly onto the Call Stack
b) Into the Task Queue (or Macrotask Queue)
c) Into the Garbage Collector
d) Into the Global Lexical Environment
Correct Answer: b) Into the Task Queue (or Macrotask Queue)
Explanation:
When asynchronous operations finish, their callbacks are queued in the Task Queue, waiting for the call stack to clear.

4. Which queue has a higher priority in the JavaScript event loop: the Microtask Queue or the Macrotask Queue?

a) Macrotask Queue
b) Microtask Queue
c) They share equal priority and alternate randomly
d) Task Queue executes first
Correct Answer: b) Microtask Queue
Explanation:
The event loop checks and empties the entire Microtask Queue before moving on to any macrotask.

5. Which of the following operations schedules a microtask?

a) setTimeout()
b) setInterval()
c) Promise.prototype.then() / catch() / finally()
d) requestAnimationFrame()
Correct Answer: c) Promise.prototype.then() / catch() / finally()
Explanation:
Settled promise callbacks and queueMicrotask() explicitly place callback jobs into the microtask queue.

6. Which of the following is considered a macrotask?

a) queueMicrotask()
b) Promise resolution callback
c) setTimeout()
d) process.nextTick() (in Node.js)
Correct Answer: c) setTimeout()
Explanation:
setTimeout, setInterval, setImmediate, and I/O events are placed in the macrotask queue.

7. What is 'Callback Hell' (or the Pyramid of Doom)?

a) An infinite loop caused by recursive function calls
b) Deeply nested callback functions resulting from multiple asynchronous operations depending on one another
c) A runtime error thrown when a callback is undefined
d) A security vulnerability in asynchronous event listeners
Correct Answer: b) Deeply nested callback functions resulting from multiple asynchronous operations depending on one another
Explanation:
Callback hell occurs when multiple asynchronous tasks are chained using nested callbacks, creating unmaintainable code.

8. What problem do JavaScript Promises solve compared to traditional error-first callbacks?

a) They make JavaScript multi-threaded.
b) They eliminate callback hell by providing cleaner chaining (.then) and centralized error handling (.catch).
c) They convert asynchronous code into synchronous blocking code.
d) They remove the need for the event loop.
Correct Answer: b) They eliminate callback hell by providing cleaner chaining (.then) and centralized error handling (.catch).
Explanation:
Promises provide a standardized abstraction for asynchronous results, enabling fluent chaining.

9. What are the three possible states of a JavaScript Promise?

a) Pending, Fulfilled, Rejected
b) Active, Waiting, Completed
c) Loading, Success, Failure
d) Uninitialized, Running, Terminated
Correct Answer: a) Pending, Fulfilled, Rejected
Explanation:
A promise starts in 'pending', then settles into either 'fulfilled' or 'rejected'.

10. Can a Promise transition from 'fulfilled' to 'rejected'?

a) Yes, if an exception is thrown inside a .then handler
b) No, a promise state is immutable once settled (fulfilled or rejected)
c) Yes, using promise.reset()
d) Only when garbage collected
Correct Answer: b) No, a promise state is immutable once settled (fulfilled or rejected)
Explanation:
Once a promise is fulfilled or rejected, its state and value cannot change.

11. What does `Promise.resolve(value)` return?

a) A new Promise object that is already fulfilled with the given value
b) The raw value itself
c) A pending promise
d) An error if the value is not a promise
Correct Answer: a) A new Promise object that is already fulfilled with the given value
Explanation:
Promise.resolve() creates a promise resolved with the passed value.

12. What does `Promise.reject(reason)` return?

a) A rejected promise with the specified reason/error
b) Throws a synchronous error immediately
c) A pending promise
d) Undefined
Correct Answer: a) A rejected promise with the specified reason/error
Explanation:
Promise.reject returns a promise rejected with the provided reason object.

13. What is the purpose of `Promise.all([p1, p2, p3])`?

a) It waits for all input promises to fulfill and returns an array of their fulfillment values. If any promise rejects, the entire returned promise rejects immediately.
b) It returns the result of the fastest promise.
c) It runs promises sequentially one after another.
d) It ignores rejected promises and returns only successful results.
Correct Answer: a) It waits for all input promises to fulfill and returns an array of their fulfillment values. If any promise rejects, the entire returned promise rejects immediately.
Explanation:
Promise.all fails fast if any single promise in the iterable rejects.

14. How does `Promise.allSettled([p1, p2, p3])` differ from `Promise.all()`?

a) Promise.allSettled waits for all promises to settle and returns an array of status objects for each promise, never failing early.
b) Promise.allSettled rejects faster.
c) Promise.allSettled only works with two promises.
d) There is no difference.
Correct Answer: a) Promise.allSettled waits for all promises to settle and returns an array of status objects for each promise, never failing early.
Explanation:
Promise.allSettled gives the outcome of every promise regardless of failure.

15. What does `Promise.race([p1, p2, p3])` return?

a) A promise that fulfills or rejects as soon as any one of the input promises settles
b) The promise with the largest value
c) The slowest resolving promise
d) An array of all settled promises
Correct Answer: a) A promise that fulfills or rejects as soon as any one of the input promises settles
Explanation:
Promise.race settles as soon as the first promise in the iterable wins the race.

16. How does `Promise.any([p1, p2, p3])` behave?

a) It fulfills as soon as *any* of the input promises fulfills, ignoring rejections unless *all* input promises reject.
b) It rejects as soon as the first promise rejects.
c) It waits for all promises to reject.
d) It returns the first rejected promise.
Correct Answer: a) It fulfills as soon as *any* of the input promises fulfills, ignoring rejections unless *all* input promises reject.
Explanation:
Promise.any looks for the first success; it only rejects with an AggregateError if every single input promise fails.

17. What is the purpose of the `async` keyword preceding a function declaration?

a) It automatically makes the function return a Promise, allowing the use of `await` inside it.
b) It spawns a new OS thread for execution.
c) It disables error logging.
d) It makes function execution synchronous.
Correct Answer: a) It automatically makes the function return a Promise, allowing the use of `await` inside it.
Explanation:
An async function implicitly wraps its return value in a resolved promise.

18. What does the `await` operator do inside an `async` function?

a) It pauses the execution of the async function until the awaited promise settles, resuming execution with the resolved value without blocking the main thread.
b) It blocks the entire JavaScript thread until the promise resolves.
c) It cancels the promise if it takes too long.
d) It converts synchronous code into a web worker.
Correct Answer: a) It pauses the execution of the async function until the awaited promise settles, resuming execution with the resolved value without blocking the main thread.
Explanation:
await suspends the execution of the async function context, returning control to the event loop.

19. How should errors be caught in `async/await` code?

a) Using standard synchronous `try...catch` blocks
b) Using `.catch()` handlers exclusively
c) Errors cannot be caught in async functions
d) Using `window.onerror`
Correct Answer: a) Using standard synchronous `try...catch` blocks
Explanation:
Rejected promises awaited inside an async function throw an exception that can be caught using standard try...catch.

20. What is the output of `setTimeout(fn, 0)`?

a) Executes `fn` instantly on the call stack
b) Schedules `fn` to run as soon as the call stack is empty and all microtasks have run, with a minimum browser-enforced delay.
c) Executes `fn` in a background thread in exactly 0 milliseconds.
d) Throws a timeout error
Correct Answer: b) Schedules `fn` to run as soon as the call stack is empty and all microtasks have run, with a minimum browser-enforced delay.
Explanation:
A 0ms timeout pushes the callback to the macrotask queue after clearing the call stack and microtask queue.

21. What is 'Top-Level Await' introduced in ES2022?

a) The ability to use the `await` keyword at the top level of an ES module without wrapping it in an async function
b) A way to await promises in global script tags
c) A method to pause server startup
d) A multithreading construct
Correct Answer: a) The ability to use the `await` keyword at the top level of an ES module without wrapping it in an async function
Explanation:
Modules can now use await at the top level, making modules act as large async functions.

22. What is an Asynchronous Generator function?

a) A generator function declared with `async function*` that yields promises and can be iterated using `for await...of`
b) A generator that runs in a web worker
c) A regular function that returns callbacks
d) A function that generates random async events
Correct Answer: a) A generator function declared with `async function*` that yields promises and can be iterated using `for await...of`
Explanation:
Async generators yield promises and allow asynchronous iteration over streams of data.

23. What does the `for await...of` loop do?

a) It iterates over async iterables or sync iterables, awaiting each yielded promise before proceeding to the next iteration.
b) It runs loops in parallel threads.
c) It loops infinitely until interrupted.
d) It replaces `for...in` for object keys.
Correct Answer: a) It iterates over async iterables or sync iterables, awaiting each yielded promise before proceeding to the next iteration.
Explanation:
for await...of pauses loop iteration until each awaited promise resolves.

24. What is the purpose of `AbortController` in modern asynchronous JavaScript (such as with `fetch`)?

a) To abort ongoing asynchronous fetch requests or operations using an `AbortSignal`
b) To restart crashed web workers
c) To cancel event listeners automatically
d) To control browser window navigation
Correct Answer: a) To abort ongoing asynchronous fetch requests or operations using an `AbortSignal`
Explanation:
AbortController provides a standard way to cancel ongoing fetch requests.

25. What happens if a Promise is rejected and no `.catch()` or rejection handler is attached?

a) An 'unhandledrejection' event fires on the global window or process, potentially logging an unhandled rejection warning.
b) The application crashes immediately.
c) The error is silently ignored with no trace.
d) The browser reloads automatically.
Correct Answer: a) An 'unhandledrejection' event fires on the global window or process, potentially logging an unhandled rejection warning.
Explanation:
Modern runtimes emit unhandledrejection events to alert developers about neglected promise rejections.

26. What is the difference between executing async tasks in *sequence* versus *parallel* using `async/await`?

a) Sequential execution awaits each task one after another, whereas parallel execution initiates all promises simultaneously and awaits them together via Promise.all.
b) Parallel execution requires multiple threads, while sequential uses one.
c) There is no performance difference.
d) Sequential execution prevents all errors.
Correct Answer: a) Sequential execution awaits each task one after another, whereas parallel execution initiates all promises simultaneously and awaits them together via Promise.all.
Explanation:
Starting promises before awaiting runs them concurrently, reducing total execution time.

27. What is a race condition in asynchronous programming?

a) A bug where the output depends on the non-deterministic timing or interleaving of unpredictable asynchronous operations
b) A performance benchmark comparing async speed
c) An animation rendering bottleneck
d) A deadlock in thread synchronization
Correct Answer: a) A bug where the output depends on the non-deterministic timing or interleaving of unpredictable asynchronous operations
Explanation:
Race conditions occur when async operations finish in an unexpected order, corrupting state.

28. How does `setInterval(fn, delay)` behave if callback execution takes longer than the delay interval?

a) Interval callbacks can queue up back-to-back or overlap without skipping delays depending on execution duration.
b) The browser automatically doubles the delay.
c) The execution stops permanently.
d) Intervals guarantee exact fixed spacing.
Correct Answer: a) Interval callbacks can queue up back-to-back or overlap without skipping delays depending on execution duration.
Explanation:
setInterval fires timers at fixed intervals regardless of whether the previous callback finished.

29. Why is using recursive `setTimeout` often preferred over `setInterval` for precise periodic polling?

a) It guarantees a fixed delay between the *end* of one execution and the *start* of the next, preventing overlapping pileups.
b) It uses less memory.
c) It runs in a separate worker thread.
d) It executes synchronously.
Correct Answer: a) It guarantees a fixed delay between the *end* of one execution and the *start* of the next, preventing overlapping pileups.
Explanation:
Recursive setTimeout schedules the next timeout only after the current callback completes.

30. What does `queueMicrotask(callback)` do?

a) Queues a microtask safely to be executed before control returns to the event loop's macrotask queue
b) Queues a macrotask with zero delay
c) Spawns a micro-worker thread
d) Clears all pending promises
Correct Answer: a) Queues a microtask safely to be executed before control returns to the event loop's macrotask queue
Explanation:
queueMicrotask is a clean API for executing custom code as a microtask.

31. What is the purpose of `Promise.prototype.finally()`?

a) To execute cleanup code regardless of whether the promise was fulfilled or rejected
b) To force a promise to fulfill successfully
c) To terminate a hanging promise
d) To catch uncaught exceptions
Correct Answer: a) To execute cleanup code regardless of whether the promise was fulfilled or rejected
Explanation:
finally() runs when a promise settles, passing through the original resolution or rejection.

32. What is asynchronous debouncing?

a) A technique to delay function execution until a specified amount of time has elapsed since the last time it was invoked
b) Executing async tasks immediately
c) Canceling promises on button click
d) Retrying failed network requests
Correct Answer: a) A technique to delay function execution until a specified amount of time has elapsed since the last time it was invoked
Explanation:
Debouncing groups multiple rapid events into a single delayed execution.

33. What is asynchronous throttling?

a) A technique ensuring a function is called at most once in a specified time period, no matter how many times triggered
b) Slowing down CPU speed
c) Limiting network bandwidth
d) Queuing promises sequentially
Correct Answer: a) A technique ensuring a function is called at most once in a specified time period, no matter how many times triggered
Explanation:
Throttling guarantees regular execution intervals during continuous events.

34. What is a Web Worker in JavaScript?

a) A script running in a background thread separate from the main execution thread, enabling true parallel computation in the browser
b) An asynchronous callback function wrapper
c) A server-side Node.js cluster node
d) A fetch request interceptor
Correct Answer: a) A script running in a background thread separate from the main execution thread, enabling true parallel computation in the browser
Explanation:
Web Workers allow running CPU-intensive JavaScript tasks in background threads.

35. Can Web Workers directly manipulate the DOM?

a) No, Web Workers do not have access to the window, document, or DOM.
b) Yes, using special worker DOM APIs.
c) Yes, if run in synchronous mode.
d) Only in Safari and Chrome.
Correct Answer: a) No, Web Workers do not have access to the window, document, or DOM.
Explanation:
Workers communicate with the main thread via message passing because they lack DOM access.

36. How do the main thread and a Web Worker communicate?

a) Via asynchronous message passing using `postMessage()` and `onmessage` event handlers
b) By sharing global variables in memory
c) Using synchronous function calls
d) Through local storage events
Correct Answer: a) Via asynchronous message passing using `postMessage()` and `onmessage` event handlers
Explanation:
Workers communicate by cloning or transferring data messages across thread boundaries.

37. What is Event Delegation in asynchronous UI handling?

a) Attaching a single event listener to a parent element to handle events triggered on its descendants via bubbling
b) Delegating async tasks to Web Workers
c) Passing callbacks between promises
d) Canceling async requests
Correct Answer: a) Attaching a single event listener to a parent element to handle events triggered on its descendants via bubbling
Explanation:
Event delegation optimizes memory and handles dynamically added elements efficiently.

38. What is memoization in the context of asynchronous function calls?

a) Caching the results of expensive asynchronous function calls based on input parameters to avoid redundant operations
b) Storing promises in local storage
c) Compressing JSON responses
d) Garbage collecting old promises
Correct Answer: a) Caching the results of expensive asynchronous function calls based on input parameters to avoid redundant operations
Explanation:
Memoization saves resolved promise results for identical future inputs.

39. What is the execution order when mixing synchronous logs, setTimeout, and Promise resolves?

a) Sync code -> Microtasks (Promises) -> Macrotasks (setTimeout)
b) Macrotasks -> Microtasks -> Sync code
c) Sync code -> Macrotasks -> Microtasks
d) All execute simultaneously
Correct Answer: a) Sync code -> Microtasks (Promises) -> Macrotasks (setTimeout)
Explanation:
The event loop clears synchronous call stack first, then all microtasks, and finally macrotasks.

40. What is an Exponential Backoff retry strategy in asynchronous networking?

a) A strategy where failed network requests are retried with progressively longer delays to prevent server overload
b) Retrying requests every millisecond infinitely
c) Aborting requests immediately on failure
d) Compressing retry payloads
Correct Answer: a) A strategy where failed network requests are retried with progressively longer delays to prevent server overload
Explanation:
Exponential backoff helps gracefully handle temporary network hiccups without flooding servers.

41. What is a Promise Pool in asynchronous JavaScript concurrency management?

a) A utility or pattern that limits the number of concurrently executing promises out of a large batch
b) A pool of reusable promise objects in memory
c) A database connection pool
d) A collection of rejected promises
Correct Answer: a) A utility or pattern that limits the number of concurrently executing promises out of a large batch
Explanation:
Promise pools prevent overwhelming APIs or resources by throttling concurrent requests.

42. What is the purpose of `requestAnimationFrame()` in browser asynchronous timing?

a) To queue a callback to be executed before the browser performs the next repaint, ensuring smooth animations
b) To delay execution by 1 second
c) To run background tasks in Web Workers
d) To fetch animation assets
Correct Answer: a) To queue a callback to be executed before the browser performs the next repaint, ensuring smooth animations
Explanation:
rAF is optimized for visual animations, syncing execution with the display refresh cycle.

43. What is the difference between `setTimeout` and `setImmediate` in Node.js?

a) setImmediate executes callbacks in the check phase, whereas setTimeout with 0ms executes in the timers phase.
b) They are identical.
c) setImmediate is synchronous.
d) setTimeout runs before microtasks.
Correct Answer: a) setImmediate executes callbacks in the check phase, whereas setTimeout with 0ms executes in the timers phase.
Explanation:
In Node.js event loop phases, setImmediate and setTimeout(..., 0) handle phase separation.

44. What is an asynchronous mutex or lock?

a) A synchronization primitive used to ensure that only one asynchronous operation accesses a critical shared resource at a time
b) A password hashing function
c) A security SSL certificate
d) A method to freeze browser tabs
Correct Answer: a) A synchronization primitive used to ensure that only one asynchronous operation accesses a critical shared resource at a time
Explanation:
Async mutexes prevent race conditions in single-threaded async code modifying shared state.

45. What does `fetch()` return upon invocation?

a) A Promise that resolves to a Response object representing the response to the request
b) The raw JSON string directly
c) A synchronous response object
d) An error if offline
Correct Answer: a) A Promise that resolves to a Response object representing the response to the request
Explanation:
fetch returns a promise resolving to a Response object; it does not reject on HTTP error statuses.

46. Does `fetch()` reject on receiving an HTTP 404 or 500 error status?

a) No, fetch only rejects on network failure; HTTP error statuses result in a fulfilled promise with `response.ok` set to false.
b) Yes, it rejects automatically.
c) Only on 500 errors.
d) Yes, if headers are missing.
Correct Answer: a) No, fetch only rejects on network failure; HTTP error statuses result in a fulfilled promise with `response.ok` set to false.
Explanation:
Developers must manually check `response.ok` or `response.status` to handle HTTP error codes.

47. How do you parse JSON data from a `fetch` Response object asynchronously?

a) By calling `response.json()`, which returns a Promise resolving to the parsed JavaScript object
b) Using `JSON.parse(response)` synchronously
c) Using `response.parse()`
d) JSON is parsed automatically without methods.
Correct Answer: a) By calling `response.json()`, which returns a Promise resolving to the parsed JavaScript object
Explanation:
response.json() reads the response stream to completion and parses it as JSON asynchronously.

48. What is the Temporal Dead Zone (TDZ) and does it affect async functions?

a) It is the region where let/const variables are uninitialized before declaration; it affects async function bodies just like synchronous code.
b) It is a timeout delay zone for promises.
c) It only affects var declarations.
d) It applies exclusively to Web Workers.
Correct Answer: a) It is the region where let/const variables are uninitialized before declaration; it affects async function bodies just like synchronous code.
Explanation:
TDZ scoping rules apply uniformly to all block scopes, including async function scopes.

49. What is the output when you await a non-promise value in an async function?

a) The value is automatically wrapped in a resolved promise and evaluated immediately.
b) It throws a TypeError.
c) It is treated as undefined.
d) It blocks execution permanently.
Correct Answer: a) The value is automatically wrapped in a resolved promise and evaluated immediately.
Explanation:
Awaiting a non-promise value treats it as if it were `Promise.resolve(value)`.

50. What is asynchronous request batching?

a) Combining multiple individual asynchronous requests into a single batched network payload to reduce HTTP overhead
b) Executing requests in random order
c) Canceling duplicate requests
d) Queuing requests in local storage
Correct Answer: a) Combining multiple individual asynchronous requests into a single batched network payload to reduce HTTP overhead
Explanation:
Batching optimizes network performance by reducing round trips to servers.

51. What is a Promise leak?

a) A situation where promises or their handlers retain memory references or leave handlers unattached, preventing garbage collection
b) A memory leak caused by open database sockets
c) Leaking promise source code in bundles
d) A network timeout leak
Correct Answer: a) A situation where promises or their handlers retain memory references or leave handlers unattached, preventing garbage collection
Explanation:
Unresolved dangling promises or uncleared event listeners can cause memory retention.

52. What is the purpose of `queueMicrotask()` compared to `Promise.resolve().then()`?

a) queueMicrotask() provides a clean, explicit semantic API specifically for queuing microtasks without needing to instantiate dummy Promise objects.
b) queueMicrotask runs as a macrotask.
c) Promise.then is faster than queueMicrotask.
d) They have entirely different execution queues.
Correct Answer: a) queueMicrotask() provides a clean, explicit semantic API specifically for queuing microtasks without needing to instantiate dummy Promise objects.
Explanation:
Both schedule microtasks, but queueMicrotask is designed explicitly for that purpose.

53. How can you implement a timeout wrapper around a Promise that rejects if it takes too long?

a) Using `Promise.race()` combined with a `setTimeout` promise that rejects after X milliseconds
b) Using `promise.setTimeout()` method
c) Using `fetch` timeout headers only
d) Using synchronous sleep loops
Correct Answer: a) Using `Promise.race()` combined with a `setTimeout` promise that rejects after X milliseconds
Explanation:
Racing a target promise against a rejecting timer promise is the standard pattern for promise timeouts.

54. What is asynchronous lazy loading (code splitting)?

a) Loading asynchronous chunks of JavaScript code on-demand using dynamic `import()` only when needed
b) Delaying image downloads until mouseover
c) Caching API responses in memory
d) Running code in Web Workers
Correct Answer: a) Loading asynchronous chunks of JavaScript code on-demand using dynamic `import()` only when needed
Explanation:
Dynamic import() returns a promise that resolves to the module, enabling efficient bundle code splitting.

55. What does dynamic `import()` return?

a) A Promise that resolves to the module namespace object of the requested module
b) The module content synchronously
c) A boolean status
d) An error if cached
Correct Answer: a) A Promise that resolves to the module namespace object of the requested module
Explanation:
Dynamic imports are asynchronous and return promises resolving to the imported module.

56. What is the primary danger of unhandled promise rejections in Node.js applications?

a) It emits warnings or can terminate the process depending on configuration, hiding silent runtime bugs.
b) It corrupts database files.
c) It causes infinite CPU loops.
d) It disables garbage collection.
Correct Answer: a) It emits warnings or can terminate the process depending on configuration, hiding silent runtime bugs.
Explanation:
Unhandled rejections are dangerous because silent failures can hide critical runtime bugs.

57. What is the execution order difference between `process.nextTick()` and `Promise.resolve()` in Node.js?

a) In Node.js, `process.nextTick()` callbacks are queued in the nextTick queue, which runs *even before* standard Promise microtasks.
b) Promise microtasks run before nextTick.
c) They are executed in random order.
d) nextTick is a macrotask.
Correct Answer: a) In Node.js, `process.nextTick()` callbacks are queued in the nextTick queue, which runs *even before* standard Promise microtasks.
Explanation:
Node's nextTick queue has the highest priority of all microtask queues in the Node event loop.

58. What is an asynchronous retry wrapper pattern?

a) A higher-order wrapper function that catches asynchronous failures and re-attempts execution up to a maximum number of attempts
b) A function that restarts the browser
c) A recursive timeout loop
d) A promise cancellation utility
Correct Answer: a) A higher-order wrapper function that catches asynchronous failures and re-attempts execution up to a maximum number of attempts
Explanation:
Retry wrappers enhance application resilience against transient failures.

59. How does `async/await` handle arrays in loops like `forEach`?

a) `Array.prototype.forEach` does not wait for async callbacks or `await`; a standard `for...of` loop should be used instead for sequential async operations.
b) forEach automatically runs async callbacks in parallel and awaits them all.
c) forEach pauses until all callbacks finish.
d) forEach throws a SyntaxError with await.
Correct Answer: a) `Array.prototype.forEach` does not wait for async callbacks or `await`; a standard `for...of` loop should be used instead for sequential async operations.
Explanation:
forEach ignores return values and async functions, completing immediately without waiting.

60. What is the result of running multiple async tasks in parallel using `Promise.all` inside a loop?

a) Mapping items to async functions produces an array of promises, which can then be passed to `Promise.all()` to execute concurrently.
b) It runs them sequentially.
c) It causes a deadlock.
d) It throws a TypeError.
Correct Answer: a) Mapping items to async functions produces an array of promises, which can then be passed to `Promise.all()` to execute concurrently.
Explanation:
Array.map combined with Promise.all is the classic idiom for parallel async mapping.

61. What is a deadlock in asynchronous programming concurrency?

a) A state where two or more asynchronous operations are waiting indefinitely for each other to release resources or resolve
b) A network timeout
c) A memory leak
d) An unhandled promise rejection
Correct Answer: a) A state where two or more asynchronous operations are waiting indefinitely for each other to release resources or resolve
Explanation:
Deadlocks occur in poorly synchronized resource locking across async tasks.

62. What is the purpose of `navigator.sendBeacon()` in asynchronous web development?

a) To asynchronously transmit small amounts of analytics or diagnostic data to a server safely, even as the user navigates away
b) To send push notifications
c) To ping web sockets
d) To check internet connectivity
Correct Answer: a) To asynchronously transmit small amounts of analytics or diagnostic data to a server safely, even as the user navigates away
Explanation:
sendBeacon uses the browser background queue to ensure telemetry data transmits during page unloads.

63. What is an asynchronous observable (e.g., RxJS)?

a) A declarative data stream representation that can emit multiple values over time to multiple subscribers, unlike single-value Promises
b) An alias for a Promise
c) A DOM mutation observer
d) A web worker stream
Correct Answer: a) A declarative data stream representation that can emit multiple values over time to multiple subscribers, unlike single-value Promises
Explanation:
Observables handle streams of multiple asynchronous events over time.

64. How do Promises handle exceptions thrown inside `.then()` callbacks?

a) The promise returned by `.then()` automatically rejects with the thrown error.
b) The application crashes immediately.
c) The error is ignored.
d) The error is caught by synchronous try/catch outside the promise chain.
Correct Answer: a) The promise returned by `.then()` automatically rejects with the thrown error.
Explanation:
Exceptions thrown inside `.then` or `.catch` handlers result in rejection of the chained promise.

65. What is the difference between `Promise.all` and `Promise.allSettled` when all promises succeed?

a) Both fulfill successfully, but `Promise.all` returns an array of raw values, whereas `Promise.allSettled` returns an array of status objects.
b) Promise.allSettled is slower.
c) Promise.all returns status objects.
d) There is no difference in return structure.
Correct Answer: a) Both fulfill successfully, but `Promise.all` returns an array of raw values, whereas `Promise.allSettled` returns an array of status objects.
Explanation:
The output schemas differ: raw values vs `{status, value/reason}` objects.

66. What is an asynchronous event emitter pattern?

a) A design pattern where named events can be triggered and listened to asynchronously using event listener callbacks
b) A DOM click listener
c) A promise chaining helper
d) A web socket server
Correct Answer: a) A design pattern where named events can be triggered and listened to asynchronously using event listener callbacks
Explanation:
Event emitters manage pub-sub event dispatching.

67. What is the role of the JS runtime Garbage Collector in asynchronous memory management?

a) It reclaims memory occupied by objects and closures once they are no longer reachable or referenced by active execution contexts or lingering async listeners.
b) It clears the task queue automatically.
c) It resets promises to pending state.
d) It terminates slow async functions.
Correct Answer: a) It reclaims memory occupied by objects and closures once they are no longer reachable or referenced by active execution contexts or lingering async listeners.
Explanation:
Garbage collection cleans up unreferenced memory, though dangling listeners can prevent collection.

68. What is a 'fire-and-forget' asynchronous function call?

a) Invoking an async function or promise without awaiting its result or attaching error handlers
b) Deleting promises from memory
c) Canceling a fetch request
d) A promise that never resolves
Correct Answer: a) Invoking an async function or promise without awaiting its result or attaching error handlers
Explanation:
Fire-and-forget runs async tasks in the background without waiting for completion, risking unhandled rejections.

69. What is the output of chaining `.catch()` after another `.catch()` in a Promise chain?

a) The second catch handles any errors thrown or rejections produced within the first catch handler
b) It causes a syntax error
c) It resets the promise state
d) It is ignored
Correct Answer: a) The second catch handles any errors thrown or rejections produced within the first catch handler
Explanation:
Catch handlers return resolved promises unless they throw an error, allowing subsequent catches to handle errors.

70. What is asynchronous throttling vs debouncing summarized correctly?

a) Throttling executes at a regular fixed rate over time, whereas debouncing waits for a quiet pause in events before executing once.
b) They are identical techniques.
c) Debouncing runs faster than throttling.
d) Throttling delays execution infinitely.
Correct Answer: a) Throttling executes at a regular fixed rate over time, whereas debouncing waits for a quiet pause in events before executing once.
Explanation:
Throttle guarantees regular pulses; debounce groups bursts into a single trailing execution.

71. What is the primary benefit of using `async/await` over raw `.then()` chains?

a) It allows writing asynchronous code that looks and behaves like synchronous code, improving readability and simplifying complex try/catch error handling.
b) It executes asynchronous tasks faster.
c) It removes the need for promises.
d) It prevents memory leaks automatically.
Correct Answer: a) It allows writing asynchronous code that looks and behaves like synchronous code, improving readability and simplifying complex try/catch error handling.
Explanation:
Async/await syntactic sugar flattens promise chains and simplifies control flow.

72. Can you use `await` outside of an `async` function in standard scripts (non-modules)?

a) No, using `await` outside of an async function or top-level module throws a SyntaxError.
b) Yes, it works anywhere in global scope.
c) Yes, but only in strict mode.
d) Yes, it defaults to an async wrapper.
Correct Answer: a) No, using `await` outside of an async function or top-level module throws a SyntaxError.
Explanation:
Standard global scripts do not support top-level await unless configured as ES modules.

73. What is an asynchronous lock mechanism used for in distributed or client-side web workers?

a) To coordinate exclusive access to resources across asynchronous workers or tabs
b) To lock browser UI rendering
c) To encrypt promise payloads
d) To pause garbage collection
Correct Answer: a) To coordinate exclusive access to resources across asynchronous workers or tabs
Explanation:
Locks prevent concurrent data corruption in shared storage or worker databases.

74. What is the lifecycle phase where Node.js processes timers like `setTimeout`?

a) The timers phase of the Libuv event loop
b) The check phase
c) The poll phase
d) The microtask phase
Correct Answer: a) The timers phase of the Libuv event loop
Explanation:
Libuv event loop processes expired setTimeout and setInterval callbacks in the timers phase.

75. What is the purpose of `Promise.any()` when all promises reject?

a) It rejects with an `AggregateError` containing all individual rejection reasons.
b) It resolves with undefined.
c) It returns an empty array.
d) It hangs indefinitely.
Correct Answer: a) It rejects with an `AggregateError` containing all individual rejection reasons.
Explanation:
AggregateError bundles all rejections when Promise.any fails to find any successful fulfillment.

76. How do you cancel a pending `setTimeout` timer before it executes?

a) By passing the timer identifier to `clearTimeout(timerId)`
b) By calling `timer.cancel()`
c) By setting `timerId = null`
d) By clearing the task queue
Correct Answer: a) By passing the timer identifier to `clearTimeout(timerId)`
Explanation:
clearTimeout removes the scheduled timer callback from the timer list before execution.

77. How do you cancel a repeating `setInterval` timer?

a) By passing the interval identifier to `clearInterval(intervalId)`
b) By calling `interval.stop()`
c) By clearing the call stack
d) By throwing an error
Correct Answer: a) By passing the interval identifier to `clearInterval(intervalId)`
Explanation:
clearInterval stops further recurring executions of the interval callback.

78. What is the role of `queueMicrotask` in framework reactivity or state batching?

a) It allows frameworks to batch multiple state mutations and flush DOM updates once at the end of the current execution tick before rendering.
b) It triggers immediate synchronous page reloads.
c) It delays rendering by 1 second.
d) It clears component states.
Correct Answer: a) It allows frameworks to batch multiple state mutations and flush DOM updates once at the end of the current execution tick before rendering.
Explanation:
Microtask queuing is a primary mechanism for efficient state batching in modern frontend frameworks.

79. What is an asynchronous iterator protocol?

a) A protocol defining how objects implement `[Symbol.asyncIterator]()` returning an async iterator with `next()` returning a promise
b) A protocol for async network sockets
c) An array map method
d) A web worker stream protocol
Correct Answer: a) A protocol defining how objects implement `[Symbol.asyncIterator]()` returning an async iterator with `next()` returning a promise
Explanation:
Async iterables enable asynchronous streaming loops via `for await...of`.

80. What is the output of `Promise.resolve(10).then(val => val * 2)`?

a) A Promise resolving to 20
b) The number 20 synchronously
c) Undefined
d) A rejected promise
Correct Answer: a) A Promise resolving to 20
Explanation:
The `.then()` handler returns a new promise that resolves with the return value of the callback.

81. What happens if a `.then()` handler returns another Promise?

a) The outer promise returned by `.then()` adopts the state and settlement value of the returned inner Promise (promise flattening).
b) It throws a nested promise error.
c) It ignores the inner promise.
d) It converts the inner promise into a synchronous value.
Correct Answer: a) The outer promise returned by `.then()` adopts the state and settlement value of the returned inner Promise (promise flattening).
Explanation:
Promise chaining automatically flattens nested promises.

82. What is a memory leak hazard specific to asynchronous event listeners and timers?

a) Forgetting to remove event listeners or clear timers when components or objects are unmounted, keeping them referenced in memory.
b) Using arrow functions in setTimeout.
c) Awaiting too many promises.
d) Using async/await instead of callbacks.
Correct Answer: a) Forgetting to remove event listeners or clear timers when components or objects are unmounted, keeping them referenced in memory.
Explanation:
Lingering timers and event listeners retain closures in memory, causing leaks.

83. What is an asynchronous semaphore?

a) A synchronization construct that limits the number of concurrent accesses to a shared resource to a fixed maximum count
b) A network signal flag
c) A promise status flag
d) A web worker thread counter
Correct Answer: a) A synchronization construct that limits the number of concurrent accesses to a shared resource to a fixed maximum count
Explanation:
Semaphores control concurrency pools across asynchronous tasks.

84. What is the primary difference between synchronous and asynchronous exception handling?

a) Synchronous exceptions are caught by local try/catch blocks, whereas asynchronous exceptions require error-first arguments or promise .catch() / async try/catch.
b) Asynchronous exceptions cannot be caught.
c) Synchronous exceptions use promises.
d) There is no difference in syntax.
Correct Answer: a) Synchronous exceptions are caught by local try/catch blocks, whereas asynchronous exceptions require error-first arguments or promise .catch() / async try/catch.
Explanation:
Callbacks executed later in the event loop fall outside synchronous try/catch blocks on the initial stack.

85. What is the purpose of `queueMicrotask` in testing asynchronous code?

a) It allows flushing pending microtasks to assert promise resolution states deterministically in test assertions
b) It speeds up test execution
c) It mocks network requests
d) It clears test suites
Correct Answer: a) It allows flushing pending microtasks to assert promise resolution states deterministically in test assertions
Explanation:
Microtask flushing helps ensure promise chains settle before running assertions.

86. What is the primary architectural benefit of asynchronous programming in Node.js servers?

a) High throughput and scalability for I/O-bound operations without spawning expensive threads per client connection
b) Faster CPU math calculations
c) Elimination of all software bugs
d) Synchronous database querying
Correct Answer: a) High throughput and scalability for I/O-bound operations without spawning expensive threads per client connection
Explanation:
Non-blocking I/O allows Node.js to handle thousands of concurrent connections efficiently on a single thread.

87. How does `Promise.race()` behave if one of the input promises is already settled?

a) It immediately settles with that promise's value or reason.
b) It waits for all other promises anyway.
c) It throws an error.
d) It ignores settled promises.
Correct Answer: a) It immediately settles with that promise's value or reason.
Explanation:
Race resolves instantly if any input promise is already settled.

88. What is an asynchronous pipe or compose function utility?

a) A utility that chains multiple asynchronous functions together, passing the resolved output of one function as the input to the next
b) A network socket pipe
c) A CSS layout transformer
d) A stream compression tool
Correct Answer: a) A utility that chains multiple asynchronous functions together, passing the resolved output of one function as the input to the next
Explanation:
Async pipe/compose utilities enable functional composition of asynchronous steps.

89. What is the output of `async function test() { return 5; } test().then(alert)`?

a) Alerts 5
b) Alerts undefined
c) Throws a syntax error
d) Alerts a Promise object
Correct Answer: a) Alerts 5
Explanation:
An async function returning 5 resolves its returned promise with 5.

90. What is the danger of returning a promise inside an async function without awaiting it?

a) If the inner promise rejects, it might result in an unhandled rejection if not caught, and caller functions won't wait for completion unless awaited.
b) It causes an immediate stack overflow.
c) It blocks the main thread.
d) It deletes the promise.
Correct Answer: a) If the inner promise rejects, it might result in an unhandled rejection if not caught, and caller functions won't wait for completion unless awaited.
Explanation:
Forgetting to await or return inner promises breaks async control flow and error propagation.

91. What is the role of the Event Loop in bridging JavaScript code with browser/Node.js host environments?

a) It continuously inspects the call stack and task queues, coordinating the execution of synchronous code, microtasks, and macrotasks.
b) It compiles JavaScript into machine code.
c) It manages CSS layout rendering.
d) It handles operating system file permissions.
Correct Answer: a) It continuously inspects the call stack and task queues, coordinating the execution of synchronous code, microtasks, and macrotasks.
Explanation:
The event loop is the coordinator enabling asynchronous orchestration in single-threaded runtimes.

92. Can an asynchronous generator yield synchronous values alongside promises?

a) Yes, any value yielded in an async generator is automatically wrapped in a resolved promise.
b) No, async generators only accept promises.
c) Yes, but they execute synchronously.
d) No, it throws a TypeError.
Correct Answer: a) Yes, any value yielded in an async generator is automatically wrapped in a resolved promise.
Explanation:
Async generators normalize all yielded values into promises.

93. What is the purpose of `Promise.withResolvers()`?

a) To return an object containing a new Promise and its corresponding resolve and reject functions, avoiding scoping separation issues
b) To resolve multiple promises simultaneously
c) To cancel promises
d) To debug promise chains
Correct Answer: a) To return an object containing a new Promise and its corresponding resolve and reject functions, avoiding scoping separation issues
Explanation:
Promise.withResolvers simplifies creating deferred promises by returning { promise, resolve, reject } together.
← Previous: JavaScript Arrays & Array Methods MCQs
Next →: JavaScript Closures MCQs for Senior Developer Interviews
NewPython Strings MCQs

Python Strings MCQs

In Python, a string (str) is an immutable sequence of Unicode characters used to represent text data. Defined using single,…

By MCQs Generator
NewJavaScript DOM Manipulation MCQs

JavaScript DOM Manipulation MCQs

The Document Object Model (DOM) is a cross-platform programming interface that treats HTML and XML documents as a hierarchical tree…

By MCQs Generator
NewJavaScript Error Handling MCQs for Developer Interviews & Certification

JavaScript Error Handling MCQs for Developer Interviews & Certification

Exception and error handling in JavaScript is essential for preventing runtime crashes and maintaining application stability across complex web environments.…

By MCQs Generator