Skip to content
jshacks.dev
Fundamentals

JavaScript Interview Question Explain Promises With Examples

How to answer the promises interview question: an object for an eventual result that settles once and chains with then. See combinators and Promise.all.

9 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, TypeScript, Vite and npm logos.

A promise question in an interview rarely stops at the definition. The interviewer asks what a promise is, then asks what this chain prints, then asks you to write Promise.all from scratch, and the last two are where the preparation shows. The definition is easy: a promise is an object that stands for a value that is not available yet. The part that takes practice is the behavior around it: a promise settles exactly once, each then returns a new promise, errors skip forward until something handles them, and the callbacks run later, as microtasks. This post gives the answer in thirty seconds, then the states, chaining, error propagation, the combinators, the implementation of Promise.all, the follow-up about async and await, and the wrong answers that cost points. The examples run on Node.js 24, and every output is exact.

The answer in thirty seconds

A promise is an object representing the eventual result of an asynchronous operation. It starts pending and then settles once, either fulfilled with a value or rejected with a reason, and never changes again. You attach callbacks with then, catch and finally, each of which returns a new promise, so steps chain. The callbacks run asynchronously, after the current code finishes. Promises exist to replace nested callbacks with a flat sequence and to give asynchronous code a way to propagate errors.

JavaScript
const promise = new Promise((resolve, reject) => {
  console.log("executor runs now");
  resolve("done");
  reject(new Error("ignored"));
  resolve("also ignored");
});

promise.then((value) => console.log("then:", value));
console.log("after creating");
Text
executor runs now
after creating
then: done

The function passed to new Promise is the executor, and it runs synchronously, at once. The first call to resolve or reject settles the promise, and the later ones do nothing. The then callback is scheduled as a microtask, so it runs after after creating, even though the promise was already fulfilled. That last point comes up often, and it explains the order in most ordering puzzles.

The three states

A promise is pending, fulfilled or rejected, and a settled promise is immutable.

JavaScript
const pending = new Promise(() => {});
const fulfilled = Promise.resolve(42);
const rejected = Promise.reject(new Error("no"));
rejected.catch(() => {});

console.log(pending, fulfilled);
console.log((await Promise.allSettled([rejected]))[0].status);
Text
Promise { <pending> } Promise { 42 }
rejected

The printed form shows the state of each promise. Promise.resolve() and Promise.reject() create settled promises directly, and Promise.allSettled() is a convenient way to read the final state of the rejected one. The catch call on it marks it as handled, so Node.js does not report an unhandled rejection. The word "resolved" is used loosely: a promise can be resolved to another promise and still be pending, so the precise words for the final states are fulfilled and rejected.

Chaining and what then returns

Every then returns a new promise, and the value you return from the callback becomes the next promise's value.

JavaScript
Promise.resolve(1)
  .then((n) => n + 1)
  .then((n) => {
    console.log("got", n);
    return Promise.resolve(n * 10);
  })
  .then((n) => {
    console.log("then got", n);
  })
  .then((n) => {
    console.log("last got", n);
  });
Text
got 2
then got 20
last got undefined

Returning a plain value passes it along. Returning a promise makes the chain wait for it: the next step received 20, the resolved value, not the promise object. A callback that returns nothing passes undefined, which is why the last step prints it. This is where the most common bug in promise code lives.

JavaScript
function fetchNumber() {
  return Promise.resolve(5);
}

Promise.resolve()
  .then(() => {
    fetchNumber();
  })
  .then((value) => console.log("forgot return:", value));

Promise.resolve()
  .then(() => fetchNumber())
  .then((value) => console.log("returned:", value));
Text
forgot return: undefined
returned: 5

The first chain called fetchNumber() and dropped the result, so the next step got undefined and did not wait for the inner promise at all. If that promise rejected, nothing would be listening. Always return the promise from a callback, or use an arrow function with an expression body, which returns automatically.

Error handling

A rejection or a thrown error skips forward to the nearest catch.

JavaScript
Promise.resolve("start")
  .then((value) => {
    console.log("step 1", value);
    throw new Error("broke in step 1");
  })
  .then(() => console.log("step 2 never runs"))
  .catch((error) => {
    console.log("caught:", error.message);
    return "recovered";
  })
  .then((value) => console.log("step 3", value))
  .finally(() => console.log("finally runs either way"))
  .then((value) => console.log("after finally", value));
Text
step 1 start
caught: broke in step 1
step 3 recovered
finally runs either way
after finally recovered

A thrown error inside a then callback rejects the promise it returns, and every then without a rejection handler is skipped. The catch handles the error and, by returning a value, turns the chain back into a fulfilled one, so the next step runs. The finally callback receives no argument and runs in both cases, and the value passes through it unchanged, as the last line shows. A catch in the middle of a chain swallows the error unless you rethrow, which is another frequent source of missing error reports.

The combinators

The standard library offers four ways to wait for several promises.

JavaScript
const delay = (ms, value, fail = false) =>
  new Promise((resolve, reject) => setTimeout(() => (fail ? reject(new Error(value)) : resolve(value)), ms));

console.log(await Promise.all([delay(20, "a"), delay(5, "b")]));
console.log(await Promise.race([delay(20, "slow"), delay(5, "fast")]));
console.log(await Promise.any([delay(5, "x", true), delay(10, "y")]));

const settled = await Promise.allSettled([delay(5, "ok"), delay(5, "bad", true)]);
console.log(settled.map((s) => `${s.status}:${s.value ?? s.reason.message}`));

try {
  await Promise.all([delay(5, "fine"), delay(10, "boom", true)]);
} catch (error) {
  console.log("all rejected with:", error.message);
}
Text
[ 'a', 'b' ]
fast
y
[ 'fulfilled:ok', 'rejected:bad' ]
all rejected with: boom

Promise.all returns the values in the order of the input, not the order they finished in, and it rejects as soon as one input rejects. Promise.race settles with the first promise to settle, either way. Promise.any takes the first fulfilment and ignores rejections unless all fail, as covered in AggregateError. Promise.allSettled never rejects and reports each outcome. Knowing which to pick for a given need is a common follow-up, and the table at the end summarizes it.

Follow-up: write Promise.all

This is the implementation question, and a short correct answer is enough.

JavaScript
function promiseAll(inputs) {
  return new Promise((resolve, reject) => {
    const items = [...inputs];
    const results = new Array(items.length);
    let remaining = items.length;

    if (remaining === 0) {
      resolve(results);
      return;
    }

    items.forEach((item, index) => {
      Promise.resolve(item).then((value) => {
        results[index] = value;
        remaining -= 1;
        if (remaining === 0) resolve(results);
      }, reject);
    });
  });
}

console.log(await promiseAll([1, Promise.resolve(2), delay(5, 3)]));
console.log(await promiseAll([]));

try {
  await promiseAll([delay(10, "late"), Promise.reject(new Error("early"))]);
} catch (error) {
  console.log(error.message);
}
Text
[ 1, 2, 3 ]
[]
early

Four details earn the points. Each input is wrapped with Promise.resolve, so plain values work. Results are stored by index, so the order matches the input. A counter decides when everything has finished. An empty input resolves immediately. Passing reject as the second argument to then rejects the outer promise on the first failure, and later settlements are ignored, as the settle-once rule says. This version uses the delay helper from the previous section.

Follow-up: async and await

async functions are syntax over promises. An async function always returns a promise, and await pauses the function until a promise settles.

JavaScript
async function load(id) {
  if (id < 0) throw new RangeError("bad id");
  return `item ${id}`;
}

console.log(load(1) instanceof Promise);
console.log(await load(1));

try {
  await load(-1);
} catch (error) {
  console.log(error.name);
}

const sequential = [];
for (const id of [1, 2, 3]) {
  sequential.push(await load(id));
}
console.log(sequential);

console.log(await Promise.all([1, 2, 3].map(load)));
Text
true
item 1
RangeError
[ 'item 1', 'item 2', 'item 3' ]
[ 'item 1', 'item 2', 'item 3' ]

A thrown error inside an async function becomes a rejection, which await turns back into an exception that a try block catches. The last two lines produce the same result in different ways: the loop waits for each call before starting the next, and Promise.all starts them all at once. With real network calls that difference is the difference between the sum of the times and the longest time, and it is the first thing to look at in a slow async function.

Wrong answers that lose the point

  • "A promise runs in the background." The work belongs to whatever started it; the promise only reports the outcome.

  • "then callbacks run immediately when the promise is already fulfilled." They always run later, as microtasks.

  • "A promise can be resolved twice." The first settlement wins and the rest are ignored.

  • "async functions are synchronous until await, then parallel." The body runs synchronously until the first await; there is no parallelism, only waiting.

A mistake we hit: async inside forEach

JavaScript
const results = [];

[1, 2, 3].forEach(async (n) => {
  await delay(5, n);
  results.push(n);
});

console.log("right after forEach:", results.length);
await delay(30, "wait");
console.log("later:", results);

const proper = [];
for (const n of [1, 2, 3]) {
  await delay(5, n);
  proper.push(n);
}
console.log("with for...of:", proper);
Text
right after forEach: 0
later: [ 1, 2, 3 ]
with for...of: [ 1, 2, 3 ]

forEach ignores the promises its callback returns, so it finished at once and the code after it ran before any of the work. The results appeared later, which is why a test that checked immediately saw nothing. We hit it in a script that uploaded files and exited before the uploads finished. Use for...of with await to run one after another, or await Promise.all(items.map(fn)) to run them together.

A mistake we hit: unhandled rejections

JavaScript
process.once("unhandledRejection", (reason) => {
  console.log("unhandled:", reason.message);
});

Promise.reject(new Error("nobody listened"));
await delay(10, "tick");
Text
unhandled: nobody listened

A rejected promise with no handler is reported when the microtask queue drains. Since Node.js 15 the default is to print the error and exit with a failure code, which is the right default: it turns a silent failure into a visible one. The event handler above replaces that default only to demonstrate it. In production, log and shut down, and fix the missing catch.

Choosing between the combinators

You wantUse
All results, and stop at the first failurePromise.all()
Every outcome, success or failurePromise.allSettled()
The first to settle, either wayPromise.race()
The first success, ignoring failuresPromise.any()
Steps in orderawait in a for...of loop, or a then chain

Practical rules we follow

Return promises from callbacks. End every chain with a catch, or await it inside try. Use async and await for readability and Promise.all for parallel work. Do not wrap a promise in new Promise. Do not use async callbacks with forEach. Treat unhandled rejections as bugs. And when you explain, show the order of the output of a short chain.

Where the promises answer stops being enough

A senior question may ask about thenables and assimilation, the exact microtask counts of await, cancellation with AbortSignal, or how Promise.try and Promise.withResolvers simplify code. The answer above covers the model. The reference is in the MDN Promise page and the ECMAScript specification.

Taggedinterview
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.