JavaScript Promises Interview Questions and Answers

Explain Promise states, chaining, composition, and how asynchronous results and failures are handled.

Frequently Asked Questions

Important questions are highlighted in the sections below; select one to jump to its answer.

Theoretical JavaScript Interview Questions

Synchronous code runs as one job and does not yield until an operation completes. Asynchronous APIs let the current job finish while the host waits for work such as a network response or timer; a later callback or Promise reaction is queued for the event loop. Promises and async/await organize that continuation, but they do not make CPU-heavy JavaScript run on another thread.

Use .then(result => {}) on a Promise to handle fulfillment and .catch(error => {}) for rejections. Alternatively, use async/await with a try/catch block for more readable code. Both approaches allow you to work with the resolved value once the asynchronous operation completes.

Use the .catch() method after .then() to handle rejected Promises: promise.then(...).catch(error => {}). With async/await, wrap the await in a try/catch block. Always handle rejections to avoid unhandled promise rejection warnings and to gracefully recover from errors.

Start the operations before awaiting them, then use Promise.all([p1, p2, p3]) to await them concurrently. It returns results in input order when all fulfill. If one rejects, the returned Promise rejects with that reason, but other already-started operations continue unless the underlying API is cancelled separately.

Wrap potentially failing code in a try block. If an error is thrown, execution jumps to the catch block where you handle the error. The optional finally block always runs regardless of success or failure, making it ideal for cleanup tasks like closing connections.

Promise.race() resolves or rejects as soon as the first Promise settles. Promise.allSettled() waits for all Promises to settle and returns an array of outcome objects (with status, value or reason) regardless of success or failure. Promise.any() resolves with the first fulfilled Promise, or rejects with AggregateError if all fail.

A Promise is pending, fulfilled with a value, or rejected with a reason. Once it is fulfilled or rejected, it is settled and cannot change to another state.

The executor function runs synchronously as soon as the Promise is constructed. Handlers registered with then, catch, or finally run asynchronously as promise jobs after the current synchronous work.

then returns a new Promise. A handler's returned value fulfills that new Promise, while a returned Promise or thenable is adopted; a thrown error rejects it.

catch returns a new Promise like then. Returning a normal value from the handler handles the rejection and fulfills the next Promise with that value; throwing or returning a rejected Promise keeps the chain rejected.

No. A normally completing finally handler passes through the original fulfillment value or rejection reason. If the handler throws or returns a rejected Promise, that new failure replaces the prior outcome.

Promise reactions are queued as microtasks, so current synchronous code finishes before they run. In browsers, the microtask queue is normally drained before the next timer task begins. Exact ordering should be reasoned about from when each callback is queued.

Promise.all rejects as soon as an input rejects, but it does not cancel the other operations. They continue unless the operations provide a separate cancellation mechanism, such as an AbortController signal.

If given a Promise, Promise.resolve returns a Promise that adopts its state. For an object with a then method, it assimilates that thenable by invoking its method and adopting the resulting fulfillment or rejection, rather than fulfilling with the object itself.

No. Promise.race settles with the first input to settle, but the remaining operations continue. To stop ongoing work after a timeout or competing result, the underlying operation must support explicit cancellation.

A rejection is unhandled when no rejection handler is attached to the relevant chain before the host reports it. Attach catch at an appropriate boundary, and rethrow or return a rejected Promise when a caller still needs to know the operation failed.

JavaScript Practical and Coding Interview Questions

Problem: Write a function that returns a Promise resolving to the sum, then log the resolved value.

javascript

function sumAsync(a, b) {
  return new Promise((resolve) => resolve(a + b));
}

sumAsync(2, 3).then((total) => console.log(total));

Problem: Start with a fulfilled Promise containing the number 6, double it in a `.then()` handler, and log the result. Keep the example self-contained and use no timers.

javascript

Promise.resolve(6)
  .then(value => value * 2)
  .then(result => console.log(result));

Problem: Create three Promises without timers or external requests: two fulfill with numbers and one rejects. Recover only the rejected Promise with a fallback, wait for all three results concurrently with `Promise.all()`, and print the resulting array.

javascript

const jobs = [
  Promise.resolve(4),
  Promise.reject(new Error("unavailable")).catch(() => 0),
  Promise.resolve(9)
];

Promise.all(jobs).then(results => console.log(results));

Problem: Write a retry helper that calls an operation at most maxAttempts times and resolves with its first successful result. If every attempt fails, reject with the last error. Keep the example deterministic and do not use timers or network requests.

javascript

function retry(operation, maxAttempts) {
  if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {
    return Promise.reject(new RangeError('maxAttempts must be a positive integer'));
  }
  return (async () => {
    let lastError;
    for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
      try {
        return await operation(attempt);
      } catch (error) {
        lastError = error;
      }
    }
    throw lastError;
  })();
}

let attempts = 0;
retry(() => {
  attempts += 1;
  return attempts < 3
    ? Promise.reject(new Error('temporary'))
    : Promise.resolve('ready');
}, 3).then((value) => console.log(value, attempts));