FrontendInterviews.dev

Loading problem…

111. Promise.race

Medium•

Implement a promiseRace function that behaves like the native Promise.race.

The function takes an array of promises (or values) and returns a new Promise that settles as soon as the first input settles (either resolves or rejects).

Requirements

Core Behavior

  • Accept an array of Promises or values.
  • Return a new Promise.
  • Resolve with the value of the first Promise that resolves.
  • Reject with the reason of the first Promise that rejects.

Execution Rules

  • All inputs should be treated as Promises using Promise.resolve.
  • The result should settle as soon as the first input settles.

Edge Cases

  • Empty Array: If the input array is empty, return a Promise that never settles.
  • Non-Promise Values: Values should be treated as already resolved Promises.

Example

const fast = Promise.resolve('fast');
const slow = new Promise(resolve => setTimeout(() => resolve('slow'), 100));

promiseRace([fast, slow]).then(value => {
  console.log(value); // 'fast'
});

const error = Promise.reject('fail');
promiseRace([
  error,
  new Promise(resolve => setTimeout(() => resolve('slow'), 100))
]).catch(reason => {
  console.log(reason); // 'fail'
});

Constraints

  • Promise.race should resolve/reject with first settled promise
  • Handle non-promise values correctly
  • Handle empty arrays
Accepted22/28|Acceptance Rate78.6%