Skip to content

Latest commit

 

History

History
79 lines (54 loc) · 3.18 KB

35.implement-Promise.race.md

File metadata and controls

79 lines (54 loc) · 3.18 KB

35. implement Promise.race()

Promise.race is used to handle multiple promises concurrently, but it resolves or rejects as soon as the first promise settles (either resolves or rejects). It takes an iterable (such as an array) of promises and returns a single promise. This returned promise settles with the value or reason of the first promise that settles.

Key Features of Promise.race

  1. First Settled Promise Wins:

    • Promise.race returns a promise that resolves or rejects as soon as the first promise in the iterable settles.
    • This means the outcome (resolved value or rejection reason) is based on the earliest settling promise.
  2. Concurrent Execution:

    • All promises in the iterable are executed concurrently.
    • The returned promise does not wait for the rest of the promises to settle once the first one settles.
  3. Flexible Handling:

    • It can be used to manage both success and error scenarios quickly, depending on which promise settles first.
  4. Simplifying Timeouts:

    • Promise.race is often used to implement timeouts for async operations by racing the main promise against a timeout promise that rejects after a certain period.

Problem

https://bigfrontend.dev/problem/implement-Promise-race

Problem Description

This problem is similar to 31. implement async helper - race(), but with Promise.

The Promise.race() method returns a promise that fulfills or rejects as soon as one of the promises in an iterable fulfills or rejects, with the value or reason from that promise. source: MDN

Can you create a race() which works the same as Promise.race()?

Solution

/**
 * @param {Array<Promise>} promises
 * @return {Promise}
 */
function race(promises) {
  return new Promise((resolve, reject) => {
    promises.forEach((promise) => {
      promise.then(resolve).catch(reject);
    });
  });
}

Use Cases

  1. Fastest Response Wins
    When you want to proceed with the result of the fastest asynchronous operation, such as fetching data from multiple sources and using the quickest response.

  2. Timeouts
    When you need to enforce a timeout on an asynchronous operation, combining the original promise with a timeout promise that rejects after a certain period.

Example Usage

const promise1 = new Promise((resolve, reject) => setTimeout(resolve, 500, 'First!'));
const promise2 = new Promise((resolve, reject) => setTimeout(resolve, 100, 'Second!'));
const promise3 = new Promise((resolve, reject) => setTimeout(reject, 300, 'Error!'));

Promise.race([promise1, promise2, promise3])
  .then((value) => {
    console.log(value); // 'Second!' (the fastest one to settle)
  })
  .catch((error) => {
    console.error('The first settled promise rejected:', error);
  });

By leveraging Promise.race, developers can efficiently handle scenarios where the earliest completion (either resolve or reject) of any among several asynchronous tasks is needed, optimizing performance and responsiveness in cases where speed is crucial.