Tech Interview RoomStudy guides

JavaScript

Promises vs async/await. How do you handle errors and run work in parallel?

Intermediate · 2 min read · Lesson 8 of 12 in JavaScript

A Promise represents a value that will be available later. It is pending, then either fulfilled or rejected, and settles only once. async/await is syntax over promises: an async function always returns a promise, and await pauses that function (not the thread) until the promise settles.

Error handling

  • With promises: .catch() at the end of the chain.
  • With await: try/catch/finally.
  • An unhandled rejection triggers unhandledrejection in browsers and, by default, crashes a Node.js process.

Sequential vs parallel

Awaiting in a loop runs calls one after another. Start them together and await the group:

  • Promise.all: fails fast on the first rejection.
  • Promise.allSettled: waits for all and reports each result.
  • Promise.race: settles with the first to settle (useful for timeouts).
  • Promise.any: the first to fulfil; rejects with AggregateError only if all fail.

Example

js
const wait = (ms, v) => new Promise(r => setTimeout(() => r(v), ms));

async function sequential() {
  const a = await wait(100, 'a');
  const b = await wait(100, 'b');
  return [a, b];                       // about 200 ms
}
async function parallel() {
  const [a, b] = await Promise.all([wait(100, 'a'), wait(100, 'b')]);
  return [a, b];                       // about 100 ms
}
async function safe() {
  try {
    await Promise.reject(new Error('boom'));
  } catch (e) {
    return `handled ${e.message}`;
  }
}
parallel().then(console.log);          // [ 'a', 'b' ]
safe().then(console.log);              // handled boom

Follow-up questions interviewers ask

Try answering each one before you open it.

How do you cancel a fetch?

Pass an AbortController signal: fetch(url, { signal }), then call controller.abort(). The promise rejects with an AbortError. AbortSignal.timeout(5000) gives a ready-made timeout signal, and AbortSignal.any([...]) combines several. In React, abort in the effect's cleanup so a stale response never overwrites newer state.