Code Logo

First Settled with Promise.race()

Published at25 Jul 2026
JavaScript Functions Hard 0 views
Like0

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

Example 1
Input
[42]
Output
42
Explanation

Single element

Example 2
Input
[10,20]
Output
10
Explanation

First of two

Example 3
Input
[1,2,3]
Output
1
Explanation

First resolves first

Example 4
Input
[100,200,300]
Output
100
Explanation

First of three

Example 5
Input
[5,1,3]
Output
5
Explanation

First element wins

Algorithm Flow

Recommendation Algorithm Flow for First Settled with Promise.race()
Recommendation Algorithm Flow for First Settled with Promise.race()

Solution Approach

function solution(values) {
  var promises = values.map(function(v) {
    return Promise.resolve(v);
  });
  return Promise.race(promises);
}

Best Answers

javascript - Approach 1
function solution(values) {
  var promises = values.map(function(v) {
    return Promise.resolve(v);
  });
  return Promise.race(promises);
}