Promise.race()

ES6+

Returns a promise that fulfills or rejects as soon as one of the promises fulfills or rejects.

Syntax

Promise.race(iterable)

Parameters

iterable Iterable

An iterable of promises

Return Value

Promise

A Promise that settles with the first settled promise

Examples

JavaScript
const slow = new Promise(r => setTimeout(() => r('느림'), 500));
const fast = new Promise(r => setTimeout(() => r('빠름'), 100));

Promise.race([slow, fast])
  .then(value => console.log(value));
Output:
// '빠름'

📌 When to Use

Use Promise.race() for timeout implementations, first-response-wins scenarios, or when you need whichever promise settles first.

⚠️ Common Mistakes

Forgetting that race() rejects if the first settled promise rejects.

Passing an empty array to race() creates a forever-pending promise.

✅ Best Practices

Combine with a timeout promise: Promise.race([fetchData(), timeout(5000)]).

Consider Promise.any() if you want the first successful result, ignoring rejections.

⚡ Performance Notes

Promise.race() returns as soon as one promise settles. Other promises continue running but their results are ignored. Cancel unneeded operations if possible.

🌍 Real World Example

Fetch with Timeout

Implement a fetch wrapper that times out after a specified duration.

function fetchWithTimeout(url, options = {}, timeoutMs = 5000) {
  const fetchPromise = fetch(url, options);

  const timeoutPromise = new Promise((_, reject) => {
    setTimeout(() => {
      reject(new Error(`Request timed out after ${timeoutMs}ms`));
    }, timeoutMs);
  });

  return Promise.race([fetchPromise, timeoutPromise]);
}

// Usage
fetchWithTimeout('/api/slow-endpoint', {}, 3000)
  .then(response => response.json())
  .then(data => console.log('Success:', data))
  .catch(error => {
    if (error.message.includes('timed out')) {
      console.log('Request took too long');
    } else {
      console.log('Network error:', error.message);
    }
  });

Related Methods