Skip to content

Asynchronous JavaScript Interview Questions for Full Stack with Node.js

26 Asynchronous JavaScript questions with answers for full stack with node.js roles — 8 easy, 14 medium, 4 hard.

About Asynchronous JavaScript

Master callbacks, promises and async/await, the microtask queue, closures and this. Learn to run work in parallel or in sequence, limit concurrency, add timeouts and retries, cancel requests with AbortController, and avoid race conditions and floating promises. Interviewers test this heavily because most backend bugs in Node.js come from misunderstood async flow.

Sheet progressStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

What is a callback and what is callback hell?

Save to ▾
Show answer
A callback is a function passed to another function to run when an asynchronous task finishes, following Node's error-first convention (err, data). Callback hell is deeply nested callbacks where each async step depends on the previous one, making code hard to read, handle errors in and maintain. Promises and async/await flatten the nesting and centralise error handling with catch or try/catch.
02

What is a Promise and what are its states?

Save to ▾
Show answer
A Promise is an object representing the eventual result of an asynchronous operation. It has three states: pending, fulfilled with a value, or rejected with a reason. Once settled it never changes. You consume it with then, catch and finally, or with await. Promises chain, so returning a value or promise from then passes it to the next step.
03

How do you run async tasks in parallel versus in sequence?

Save to ▾
Show answer
// Sequential: each waits for the previous one for (const id of ids) { const user = await getUser(id); results.push(user); } // Parallel: start all, then wait together const users = await Promise.all(ids.map((id) => getUser(id))); // Use sequential only when steps depend on each other // or when you must limit load on a downstream service.
04

Why is using async callbacks inside forEach a common bug?

Save to ▾
Show answer
Array.forEach ignores the promise returned by an async callback, so it does not wait for any iteration and errors are not caught by the outer function. Code after the loop runs before the work is done. Use for...of with await for sequential processing, or map the items to promises and await Promise.all for parallel processing.
05

Convert this callback-based function to async/await: fs.readFile(path, 'utf8', (err, data) => {...}).

Save to ▾
Show answer
const fs = require('fs/promises'); async function readConfig(path) { try { const data = await fs.readFile(path, 'utf8'); return JSON.parse(data); } catch (err) { if (err.code === 'ENOENT') return {}; throw err; } } // Or wrap any callback API with util.promisify(fn).
06

What is a closure and how is it used in Node.js code?

Save to ▾
Show answer
A closure is a function that remembers variables from the scope where it was created, even after that outer function has returned. In Node it is used for middleware factories like rateLimit({ max: 100 }), private counters, memoisation and module-level state. A risk is memory leaks when closures hold large objects longer than needed, for example inside long-lived event listeners.
07

What is the difference between var, let and const?

Save to ▾
Show answer
var is function-scoped, hoisted and initialised as undefined, and can be redeclared. let and const are block-scoped and are in a temporal dead zone until declared, so accessing them early throws an error. const prevents reassignment of the binding but not mutation of an object's contents. Modern Node code uses const by default and let when reassignment is needed.
08

How do you explain asynchronous programming to a non-technical stakeholder or junior teammate?

Save to ▾
Show answer
I use a restaurant analogy. One waiter takes an order, gives it to the kitchen and serves other tables instead of waiting at the stove; when the dish is ready, the kitchen rings a bell. Node.js works the same: it starts a database or network task, handles other requests and resumes when the result is ready. Then I show a short code example with async and await.
09

Explain the difference between Promise.all, Promise.allSettled, Promise.race and Promise.any.

Save to ▾
Show answer
Promise.all resolves with all results when every promise fulfils, and rejects as soon as one rejects. Promise.allSettled waits for all and returns each status and value or reason, useful when partial failure is fine. Promise.race settles with the first promise to settle, often used for timeouts. Promise.any resolves with the first fulfilled promise and rejects only if all reject.
10

How does async/await work under the hood?

Save to ▾
Show answer
An async function always returns a promise. await pauses that function until the awaited promise settles, then resumes it with the value or throws the rejection, while the event loop keeps running other work. Internally it is built on promises and generator-like suspension. The code reads like synchronous code but is still non-blocking, and errors are handled with ordinary try/catch.
11

What is the output order of this code: console.log('A'); setTimeout(() => console.log('B'), 0); Promise.resolve().then(() => console.log('C')); console.log('D');

Save to ▾
Show answer
The output is A, D, C, B. Synchronous code runs first, printing A and D. Then the microtask queue is drained before the event loop moves to timers, so the promise callback prints C. Finally the timers phase runs the setTimeout callback and prints B. Microtasks always run before the next macrotask such as timers or I/O callbacks.
12

What are microtasks and macrotasks?

Save to ▾
Show answer
Macrotasks are scheduled work like setTimeout, setInterval, setImmediate and I/O callbacks, handled phase by phase by the event loop. Microtasks are promise reactions and queueMicrotask callbacks; they run right after the current synchronous code finishes and before the next macrotask. In Node, process.nextTick callbacks run even before promise microtasks. A long microtask chain can delay timers and I/O.
13

How do you add a timeout to a promise?

Save to ▾
Show answer
function withTimeout(promise, ms) { let timer; const timeout = new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('Timeout')), ms); }); return Promise.race([promise, timeout]).finally(() => clearTimeout(timer)); } await withTimeout(fetch(url), 3000); // For fetch, AbortSignal.timeout(3000) also cancels the request.
14

What happens if you forget to await a promise inside a try/catch?

Save to ▾
Show answer
If you call an async function without await, the try/catch only covers the synchronous part, so a later rejection escapes it and becomes an unhandled rejection that can crash the process. The function also continues before the work finishes, causing race conditions like responding before data is saved. ESLint rules such as no-floating-promises in TypeScript help catch this.
15

How does the this keyword behave in arrow functions compared to regular functions?

Save to ▾
Show answer
A regular function's this depends on how it is called: the object before the dot, undefined in strict mode for plain calls, or whatever bind, call or apply set. Arrow functions do not have their own this; they capture it lexically from the surrounding scope. That makes arrows ideal for callbacks inside class methods, but unsuitable as object methods that need this.
16

Write a retry function with exponential backoff for a flaky API call.

Save to ▾
Show answer
async function retry(fn, retries = 3, baseMs = 200) { for (let attempt = 0; ; attempt++) { try { return await fn(); } catch (err) { if (attempt >= retries) throw err; const delay = baseMs * 2 ** attempt + Math.random() * 100; await new Promise((r) => setTimeout(r, delay)); } } } await retry(() => paymentClient.getStatus(id));
17

A dashboard endpoint makes five independent database queries one after another and takes 1.5 seconds. How would you speed it up?

Save to ▾
Show answer
Because the queries are independent, run them concurrently with Promise.all so total time is close to the slowest query instead of the sum. Check that the database connection pool is large enough to serve them in parallel. Then add indexes for slow queries, cache rarely changing parts in Redis, and use Promise.allSettled if the page can render with some widgets missing.
18

How can you cancel an in-flight HTTP request in Node.js?

Save to ▾
Show answer
Use AbortController. Create a controller, pass controller.signal to fetch or to libraries that support it such as axios, and call controller.abort() when the request is no longer needed, for example when the client disconnects. AbortSignal.timeout(ms) gives a ready-made timeout signal. Aborting rejects the promise with an AbortError, which you should handle separately from real failures.
19

What is the difference between throwing an error and rejecting a promise inside an async function?

Save to ▾
Show answer
Inside an async function they behave the same: throw new Error() causes the returned promise to reject with that error. Outside async functions, a throw inside a plain callback such as setTimeout is not caught by promise handlers and becomes an uncaught exception. Always reject with Error objects, not strings, so you keep a stack trace.
20

A scheduled job processes orders with setInterval every minute, but sometimes runs overlap and duplicate emails are sent. How do you fix it?

Save to ▾
Show answer
setInterval fires regardless of whether the previous async run finished. Use a recursive setTimeout that schedules the next run only after the current one completes, or keep an isRunning flag. If several instances run, use a distributed lock in Redis or a job queue like BullMQ with unique job IDs. Also make email sending idempotent by recording sent message IDs.
21

Explain debounce and throttle and where they matter on the backend.

Save to ▾
Show answer
Debounce runs a function only after calls stop for a set time, merging bursts into one call. Throttle runs it at most once per interval. On the backend they help when batching cache invalidation, limiting webhook processing, writing metrics, or reacting to file watcher events. For API traffic you normally use a rate limiter instead, which is a server-side form of throttling.
22

Tell me about a time you had to debug a tricky asynchronous bug.

Save to ▾
Show answer
Situation: customers occasionally received two invoices. Task: I had to find why it happened only in production. Action: I added request IDs to logs and found a forEach with async callbacks plus a retry triggering a second save before the first finished. I replaced it with for...of, added a unique index on invoice number and made the job idempotent. Result: duplicates stopped completely.
23

How do you limit concurrency when calling an external API for 10,000 records?

Save to ▾
Show answer
async function runLimited(items, limit, worker) { const results = []; let i = 0; async function next() { while (i < items.length) { const idx = i++; results[idx] = await worker(items[idx]); } } await Promise.all(Array.from({ length: limit }, next)); return results; } await runLimited(records, 10, callPartnerApi); // Or use the p-limit package.
24

What are async iterators and when would you use for await...of?

Save to ▾
Show answer
An async iterator returns promises from its next() method, and for await...of consumes them one by one. In Node, readable streams, readline interfaces and many database cursors are async iterable. It is ideal for processing paginated API results or large query cursors item by item with natural backpressure, since the next chunk is not pulled until the current one is handled.
25

Two simultaneous requests both read a wallet balance, deduct money and save it, causing a wrong balance. How do you fix this race condition?

Save to ▾
Show answer
Async code interleaves between awaits, so read-modify-write is unsafe. Make the update atomic in the database: use an UPDATE with balance = balance - amount WHERE balance >= amount, or MongoDB $inc with a filter. Alternatives are row-level locks with SELECT FOR UPDATE inside a transaction, optimistic locking with a version column, or a Redis distributed lock for cross-service work.
26

Your service calls three microservices and fails completely if one is down. How would you make it more resilient?

Save to ▾
Show answer
Use Promise.allSettled so one failure does not reject everything, and return partial data with clear flags. Add timeouts to every call, retries with backoff for transient errors and a circuit breaker such as opossum to stop hammering a failing service. Provide fallbacks like cached values and log failures with correlation IDs so the issue can be traced.

Frequently asked questions

How important is Asynchronous JavaScript in Full Stack with Node.js interviews?

Master callbacks, promises and async/await, the microtask queue, closures and this. Learn to run work in parallel or in sequence, limit concurrency, add timeouts and retries, cancel requests with AbortController, and avoid race conditions and floating promises. Interviewers test this heavily because most backend bugs in Node.js come from misunderstood async flow.

How should I use the Asynchronous JavaScript sheet?

Go top to bottom — easy to hard. Answer before opening each answer, tick what you solved and save misses to Last-Minute Revision.