First Settled with Promise.race()
Write a JavaScript function that takes an array of values and uses Promise.race() to return the first value that resolves. The function creates delayed promises for each value, adding a delay proportional to the value, so smaller values resolve first.
Promise.race() is a static method that returns a Promise that settles (resolves or rejects) as soon as one of the input Promises settles. Unlike Promise.all() which waits for ALL to settle, Promise.race() resolves with the first settled value. This is useful for implementing timeouts, racing multiple data sources, and prioritizing fast responses.
The race pattern is distinct from Promise.any() (which waits for the first fulfillment, ignoring rejections) and Promise.allSettled() (which waits for all to settle without short-circuiting). Promise.race() short-circuits on the first settlement of any kind — resolve or reject.
Time complexity is O(n) for creating n promises. The race resolves in the time of the fastest promise. Space complexity is O(n) for the promises array.
Edge cases include empty array (Promise.race([]) returns a pending promise that never settles), single promise, all promises with the same delay, and ensuring the race resolves with the value from the fastest promise.
Example Input & Output
Single element
First of two
First resolves first
First of three
First element wins
Algorithm Flow

Solution Approach
Best Answers
function solution(values) {
var promises = values.map(function(v) {
return Promise.resolve(v);
});
return Promise.race(promises);
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
