Skip to content

Interview PrepAsync · Core

Promises and async/await ​

50. What is the difference between synchronous and asynchronous code? ​

The short answer

Synchronous code runs one statement after another, and each statement must finish before the next starts; while it runs, nothing else in that thread can happen. Asynchronous code starts an operation, such as a network request, and carries on without waiting; the result is handled later through a callback, a promise or await. JavaScript uses asynchronous code for anything slow, such as I/O, so that one thread can keep serving other work while it waits.

A coffee shop picture. A synchronous barista takes your order, makes the coffee, hands it over, and only then takes the next order, so the queue barely moves. An asynchronous barista takes your order, starts the machine, takes the next order while it brews, and calls your name when it is ready.

ts
// Synchronous: blocks until done
const config = JSON.parse(readFileSync('config.json', 'utf8'))    // (1)

// Asynchronous: starts the read, continues at once
readFile('orders.json', 'utf8').then((text) => {                  // (2)
  console.log('orders loaded', text.length)
})
console.log('this prints before "orders loaded"')                 // (3)
  1. Blocking. Fine at start-up, but inside a request handler it would stop the whole server while the disk reads.
  2. Non-blocking. The file is read in the background; the callback runs when it is done.
  3. Runs immediately, before the file has been read.
SynchronousAsynchronous
Waits for the resultYes, the thread is stuckNo, it carries on
Result deliveredAs the return valueLater: callback, promise, await
Good forFast, CPU-only workNetwork, disk, timers, databases
RiskFreezing the page or serverHarder to follow the order of events

Asynchronous is not parallel. Your JavaScript still runs on one thread. The waiting happens elsewhere, in the operating system or a thread pool, and the callbacks run one at a time (question 60).

51. What is callback hell, and how can it be avoided? ​

The short answer

Callback hell is code where each asynchronous step is nested inside the callback of the previous one, so the code drifts to the right in a "pyramid", error handling is repeated at every level, and the flow is hard to follow. It is avoided by using promises, which can be chained flat, and especially async/await, which makes asynchronous steps read like ordinary sequential code with one try/catch.

The pyramid, placing an order with callbacks:

ts
getUser(userId, (err, user) => {
  if (err) return done(err)
  getCart(user.id, (err, cart) => {
    if (err) return done(err)
    chargeCard(user.card, cart.total, (err, payment) => {
      if (err) return done(err)
      createOrder(cart, payment, (err, order) => {
        if (err) return done(err)
        done(null, order)
      })
    })
  })
})

Four steps, four levels of nesting, four copies of the same error check.

The same flow with async/await:

ts
async function placeOrder(userId: string) {
  const user = await getUser(userId)
  const cart = await getCart(user.id)
  const payment = await chargeCard(user.card, cart.total)
  return createOrder(cart, payment)
}

Any step that fails throws, and the caller handles it once with try/catch (question 56).

Other tools that help:

  • Name the steps as separate functions instead of inline callbacks.
  • Promisify old callback APIs: Node.js has util.promisify, and most core modules have a promise version, such as node:fs/promises.
  • Run independent steps together with Promise.all instead of nesting them (question 58).

52. What are JavaScript Promises, and what states can a Promise have? ​

The short answer

A Promise is an object that stands for a value that will be ready later, such as the result of a network request. It is in one of three states: pending, while the work is in progress; fulfilled, with a value, when it succeeded; or rejected, with a reason, usually an error, when it failed. Once it is fulfilled or rejected, it is settled and never changes again. You react to the outcome with .then, .catch and .finally, or with await.

pendingfulfilledwith a valuerejectedwith a reason.then(value).catch(err)resolverejectsettled: never changes again
One way in, two ways out, no way back. A promise waits in pending. It settles once, to fulfilled or rejected, and stays that way. The matching handlers then run.

Making and using a promise, wrapping a callback-style payment SDK:

ts
function charge(cardToken: string, pence: number): Promise<string> {
  return new Promise((resolve, reject) => {                          // (1)
    paymentSdk.charge(cardToken, pence, (err: Error | null, id?: string) => {
      if (err) reject(err)                                           // (2)
      else resolve(id!)                                              // (3)
    })
  })
}

charge('tok_visa', 1999)
  .then((paymentId) => console.log('paid', paymentId))               // (4)
  .catch((err) => console.error('payment failed', err.message))      // (5)
  .finally(() => console.log('payment attempt finished'))            // (6)
  1. The executor function runs immediately and receives resolve and reject.
  2. reject moves the promise to rejected.
  3. resolve moves it to fulfilled. Calling either a second time does nothing: a promise settles only once.
  4. .then runs with the value on success.
  5. .catch runs on failure, including errors thrown inside earlier .then callbacks.
  6. .finally runs either way, for clean-up such as hiding a spinner.

Chaining. .then returns a new promise, resolved with whatever the callback returns. If the callback returns another promise, the chain waits for it. That is how promise chains stay flat (question 51).

Promise callbacks always run asynchronously, even if the promise is already settled. They go into the microtask queue and run after the current code finishes (question 61):

ts
Promise.resolve('ready').then((v) => console.log(v))
console.log('first')
// first
// ready

53. How do async and await work? ​

The short answer

An async function always returns a promise. Inside it, await pauses that function until the awaited promise settles, then resumes it with the fulfilled value, or throws the rejection as an exception at that line. While the function is paused, the thread is free to run other code, because the rest of the function is scheduled as a microtask when the promise settles. It is promise chaining written as straight-line code.

ts
async function checkout(cartId: string) {
  console.log('1. start')
  const cart = await loadCart(cartId)            // (1)
  console.log('3. cart loaded', cart.items.length)
  const payment = await charge(cart.token, cart.totalPence)   // (2)
  return { cartId, payment }                     // (3)
}

checkout('c42').then((r) => console.log('4. done', r.payment))
console.log('2. checkout started, not finished')                // (4)
  1. await pauses checkout and returns control to the caller. Nothing else is blocked.
  2. When loadCart resolves, the function resumes here with the value, and pauses again at the next await.
  3. return resolves the promise that checkout returned.
  4. Runs before 3., because checkout paused at the first await.

It prints 1, 2, 3, then 4.

What the engine does with await. It is roughly the same as splitting the function at each await and putting the rest inside a .then:

ts
function checkoutWithThen(cartId: string) {
  console.log('1. start')
  return loadCart(cartId).then((cart) =>
    charge(cart.token, cart.totalPence).then((payment) => ({ cartId, payment })),
  )
}

The function's local variables are kept alive between the pieces, like a generator that pauses at each yield (question 46).

Things to know:

  • await only pauses its own function, never the whole program.
  • await on a non-promise value still waits one microtask, then gives back the value.
  • Top-level await works in ES modules, such as const config = await loadConfig() at the top of a file, but not in CommonJS.
  • A rejected promise becomes a thrown error at the await line, so try/catch works as usual (question 56).

54. What happens when an async function returns a value? ​

The short answer

The value is wrapped in a promise. Returning 42 from an async function gives the caller a promise that fulfils with 42; throwing an error gives a promise that rejects with that error. If you return a promise, the async function's promise follows it and settles the same way. So callers must await the result or use .then; reading the return value directly gives a promise, not the data.

ts
async function cartCount() {
  return 3                                    // (1)
}

const result = cartCount()
console.log(result)                           // (2) Promise { 3 }
console.log(await cartCount())                // (3) 3

async function loadPrice() {
  throw new Error('price service down')       // (4)
}
loadPrice().catch((e) => console.log(e.message))   // price service down
  1. A plain value is returned.
  2. The caller gets a promise, not 3. A common bug is if (isInStock()) on an async function: a promise is always truthy, so the check always passes.
  3. await unwraps it.
  4. A thrown error becomes a rejected promise, not a crash at the call site.

Returning a promise versus return await:

ts
async function getOrder(id: string) {
  try {
    return await db.orders.find(id)    // (1) errors are caught below
  } catch (err) {
    throw new NotFoundError(`order ${id}`)
  }
}
  1. Inside try, use return await. Without await, the function returns the promise straight away, the try block ends, and a later rejection is not caught by this catch. Outside a try, return promise and return await promise behave the same.

55. How do Promise.all(), Promise.allSettled(), Promise.race(), and Promise.any() differ? ​

The short answer

All four take several promises and return one. Promise.all fulfils with an array of every result, but rejects as soon as any one rejects. Promise.allSettled waits for every promise and gives you each outcome, success or failure, so it never rejects. Promise.race settles the same way as the first promise to settle, success or failure. Promise.any fulfils with the first success and only rejects, with an AggregateError, if every promise fails.

MethodFulfils whenRejects whenResult
Promise.allAll fulfilAny one rejects, immediatelyArray of values, in input order
Promise.allSettledAll settleNeverArray of { status, value } or { status, reason }
Promise.raceFirst to settle fulfilsFirst to settle rejectsOne value or one reason
Promise.anyFirst to fulfilAll rejectOne value, or an AggregateError

Each one in a real use:

ts
// all: a product page needs every part, or the page cannot render
const [product, reviews, stock] = await Promise.all([
  getProduct(id), getReviews(id), getStock(id),
])

// allSettled: send emails to many customers; one failure must not stop the rest
const results = await Promise.allSettled(customers.map((c) => sendEmail(c)))
const failed = results.filter((r) => r.status === 'rejected').length

// race: give up if the payment provider takes too long
const payment = await Promise.race([
  charge(token, pence),
  new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), 5000)),
])

// any: ask three mirrors, use whichever answers first successfully
const rates = await Promise.any([fetchRates(eu), fetchRates(us), fetchRates(asia)])

Important details:

  • Promise.all does not cancel the others when one fails. They keep running; their results are just ignored. To actually stop them, pass an AbortSignal (question 58).
  • Order is kept: results come back in the order you passed the promises, not the order they finished.
  • An empty array: Promise.all([]) fulfils at once with []; Promise.any([]) rejects at once.
  • The race timeout above leaves a timer running after the payment wins. In real code, clear it, or use AbortSignal.timeout(5000) with APIs that accept a signal.

Writing your own Promise.all is a classic task (question 98).

56. How should errors be handled with promises and async/await? ​

The short answer

With async/await, use try/catch around the awaited calls whose failures you can actually handle, and let other errors travel up to a caller or a central error handler. With promise chains, end the chain with .catch. Every promise must have its rejection handled somewhere, otherwise it becomes an unhandled rejection. Add context when you rethrow, and use finally for clean-up that must always happen.

ts
async function placeOrder(cartId: string) {
  const cart = await loadCart(cartId)                          // (1)

  let paymentId: string
  try {
    paymentId = await charge(cart.token, cart.totalPence)      // (2)
  } catch (err) {
    if (err instanceof CardDeclinedError) {
      return { ok: false, reason: 'card_declined' } as const   // (3)
    }
    throw new Error(`charge failed for cart ${cartId}`, { cause: err })   // (4)
  } finally {
    await releaseCartLock(cartId)                              // (5)
  }

  return { ok: true, paymentId } as const
}
  1. No try here: if the cart cannot load, there is nothing useful this function can do, so the error goes to the caller.
  2. A try around the step whose failures we understand.
  3. An expected failure becomes a normal result, not an exception.
  4. An unexpected failure is rethrown with context. cause keeps the original error and its stack for the logs.
  5. finally runs whether the charge worked or not, so the lock is always released.

The rules that keep error handling sane:

RuleWhy
Catch only where you can do somethingSwallowing errors hides bugs
Never catch and ignore silentlyA failed payment that is "handled" by nothing is worse than a crash
Throw Error objects, not stringsOnly Error objects carry a stack trace
Add context when rethrowing"charge failed for cart c42" beats "Request failed"
Have one top-level handlerIn Express, the error middleware; in a script, a final .catch

A common mistake: a .catch that hides the error.

ts
const user = await getUser(id).catch(() => null)   // the caller now gets null, and no log

Sometimes that is intended. More often it turns "the database is down" into "user not found".

57. Why does await inside forEach not wait? ​

The short answer

forEach calls your callback for each item and ignores what it returns. If the callback is async, each call returns a promise immediately, and forEach simply moves on to the next item without waiting. So all the work starts at once, nothing waits for it, and code after the loop runs before any of it finishes. Use for...of with await to process items one at a time, or Promise.all with map to process them together.

ts
// Wrong: logs 'all emails sent' before any email is sent
orders.forEach(async (order) => {
  await sendReceipt(order)
})
console.log('all emails sent')

// One at a time, in order
for (const order of orders) {
  await sendReceipt(order)                        // waits before the next one
}
console.log('all emails sent')                     // really true now

// All together, then wait for every one
await Promise.all(orders.map((order) => sendReceipt(order)))
console.log('all emails sent')

Why it happens: forEach is written roughly like this, with no await anywhere:

ts
function forEach<T>(list: T[], fn: (item: T) => unknown) {
  for (let i = 0; i < list.length; i++) fn(list[i])   // the returned promise is dropped
}

Errors get lost too. If one sendReceipt rejects inside forEach, nothing catches it, so it becomes an unhandled rejection (question 59).

Which replacement to choose:

NeedUse
One after another, order mattersfor...of with await
All at once, wait for allPromise.all(list.map(fn))
All at once, but some may failPromise.allSettled
Many items, limit how many run at onceA concurrency pool (question 99)

58. How do you run async work in sequence versus in parallel? ​

The short answer

To run tasks in sequence, await each one before starting the next, usually in a for...of loop; use this when each step depends on the previous one or order matters. To run independent tasks in parallel, start them all first and then wait for all of them together with Promise.all. Parallel is much faster when tasks wait on I/O, but with many tasks you should limit how many run at once, so you do not overload a database or an API.

sequenceproduct 300 msreviews 300 msstock 300 ms900 msparallelproductreviewsstock≈ 300 ms0900 ms
Waiting in line or waiting together. Three independent calls of 300 ms take 900 ms one after another, but about 300 ms when started together.
ts
// Sequence: each call waits for the previous one, about 900 ms
const product = await getProduct(id)
const reviews = await getReviews(id)
const stock = await getStock(id)

// Parallel: start all three, then wait once, about 300 ms
const [product2, reviews2, stock2] = await Promise.all([
  getProduct(id), getReviews(id), getStock(id),
])

When sequence is right: the steps depend on each other. You cannot charge a card before you know the cart total, and you should not send a receipt before the payment succeeds.

The hidden sequence bug. This looks parallel but is not:

ts
const a = await getReviews(id)     // waits
const b = await getStock(id)       // only starts after a finishes

To start both early and wait later:

ts
const reviewsP = getReviews(id)    // starts now
const stockP = getStock(id)        // starts now
const [reviews3, stock3] = await Promise.all([reviewsP, stockP])

Limit parallelism for big lists. Promise.all(10_000 items) opens 10,000 requests at once, which can exhaust database connections or hit an API's rate limit. Process them in batches, or with a pool that keeps, say, 10 running at a time (question 99).

Cancelling the rest when one fails:

ts
const controller = new AbortController()
try {
  await Promise.all(urls.map((u) => fetch(u, { signal: controller.signal })))
} catch (err) {
  controller.abort()                 // stop the requests still in flight
  throw err
}

59. What is an unhandled promise rejection? ​

The short answer

It is a promise that rejected while no .catch, try/catch around its await, or other handler was attached to it. The error has nowhere to go. In a browser it is logged to the console. In Node.js since version 15, an unhandled rejection crashes the process by default, which is deliberate: an ignored error can leave the program in a broken state. The fix is to handle every promise, and to log and exit cleanly in a last-resort handler.

How they happen:

ts
async function audit(orderId: string) {
  throw new Error('audit service down')
}

function placeOrder(orderId: string) {
  audit(orderId)                    // (1) no await, no .catch
  return 'ok'
}
  1. A "fire and forget" call. The rejection is not attached to anything, so Node.js reports it as unhandled and, by default, exits.

Fixes:

ts
// Wait for it, so the caller sees the error
await audit(orderId)

// Or fire and forget on purpose, but still handle the failure
audit(orderId).catch((err) => logger.warn({ err, orderId }, 'audit failed'))

The last-resort handler in Node.js:

ts
process.on('unhandledRejection', (reason) => {
  logger.fatal({ reason }, 'unhandled promise rejection')
  process.exitCode = 1
  shutdownGracefully()            // stop accepting requests, finish current ones, exit
})

This is for logging and a clean exit, not for carrying on as if nothing happened. The real fix is always at the source. Node.js's process-level handlers are covered further in the Node.js module.

Where unhandled rejections hide: forEach with async callbacks (question 57), event handlers that call async functions, and timers whose callbacks are async.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
JavaScript & TypeScript
Basics
Async
TypeScript
Write it yourself
Other topics
Nothing picked yet