From d32d3bccdfc9d09aec78a0907e67cddbf2adf976 Mon Sep 17 00:00:00 2001 From: Shaban-Eissa Date: Tue, 4 Jun 2024 22:29:56 +0300 Subject: [PATCH] feat: implement Promise.race() --- 35.implement-Promise.race.md | 79 ++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 35.implement-Promise.race.md diff --git a/35.implement-Promise.race.md b/35.implement-Promise.race.md new file mode 100644 index 0000000..8fa96d8 --- /dev/null +++ b/35.implement-Promise.race.md @@ -0,0 +1,79 @@ +# 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()](https://bigfrontend.dev/problem/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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race) + +Can you create a `race()` which works the same as `Promise.race()`? + +# + +### Solution + +```js +/** + * @param {Array} 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 + +```javascript +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. \ No newline at end of file