Skip to content

Commit

Permalink
feat: implement Promise.allSettled()
Browse files Browse the repository at this point in the history
  • Loading branch information
Shaban-Eissa committed Jun 4, 2024
1 parent d32d3bc commit 4ef13e9
Showing 1 changed file with 138 additions and 0 deletions.
138 changes: 138 additions & 0 deletions 33.implement-Promise.allSettled.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
# 33. implement `Promise.allSettled()`
`Promise.allSettled` is a method in JavaScript that takes an iterable (such as an array) of promises and returns a single promise. This returned promise resolves when all the promises in the iterable have settled, meaning each promise has either resolved or rejected. It does not reject if any of the promises reject; instead, it provides the outcome of each promise.

### Key Features of `Promise.allSettled`

1. **Settling of All Promises**:

* `Promise.allSettled` waits for all promises in the iterable to settle (either resolved or rejected).
* It returns a promise that resolves with an array of objects describing the outcome of each promise.
2. **Resolved Value**:

* The array contains objects with two properties: `status` and either `value` (if resolved) or `reason` (if rejected).
* Example:

```javascript
[
{ status: "fulfilled", value: result1 },
{ status: "rejected", reason: error }
]
```

3. **No Immediate Rejection**:

* Unlike `Promise.all`, it does not reject immediately if any promise rejects. Instead, it waits for all promises to settle and provides their outcomes.


### Problem

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

#

### Problem Description

> The Promise.allSettled() method returns a promise that resolves after all of the given promises have either fulfilled or rejected, with an array of objects that each describes the outcome of each promise.

from [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled)

Different from `Promise.all()` which rejects right away once an error occurs, `Promise.allSettled()` waits for all promises to settle.

Now can you implement your own `allSettled()`?

#

### Solution

```js
/**
* @param {Array<any>} promises - notice that input might contains non-promises
* @return {Promise<Array<{status: 'fulfilled', value: any} | {status: 'rejected', reason: any}>>}
*/
function allSettled(promises) {
if (promises.length === 0) {
return Promise.resolve([]);
}
const results = Array(promises.length);
let numOfSettledPromise = 0;
return new Promise((resolve, reject) => {
promises.forEach((promise, i) => {
if (!(promise instanceof Promise)) {
promise = Promise.resolve(promise);
}
promise.then(
(value) => {
results[i] = {
status: 'fulfilled',
value,
};
numOfSettledPromise++;
if (numOfSettledPromise === promises.length) {
resolve(results);
}
},
(reason) => {
results[i] = {
status: 'rejected',
reason,
};
numOfSettledPromise++;
if (numOfSettledPromise === promises.length) {
resolve(results);
}
}
);
});
});
}
```


### Example Usage

```javascript
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Promise 1 resolved");
}, 1000);
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(() => {
reject("Promise 2 rejected");
}, 2000);
});
const promise3 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Promise 3 resolved");
}, 3000);
});
PromiseAllSettled([promise1, promise2, promise3]).then((results) => {
console.log(results);
})
// output
[
{ status: 'fulfilled', value: 'Promise 1 resolved' },
{ status: 'rejected', reason: 'Promise 2 rejected' },
{ status: 'fulfilled', value: 'Promise 3 resolved' }
]
```

### Use Cases

1. **Handling Multiple Outcomes**:

* When you need to perform multiple asynchronous operations and handle each result individually, regardless of whether they succeed or fail.
2. **Ensuring All Promises Settle**:

* When you want to ensure that all promises have settled before proceeding with further logic, useful in scenarios like cleaning up resources or aggregating results.

By using `Promise.allSettled`, developers can manage multiple asynchronous operations and handle each outcome in a comprehensive manner, ensuring that all results are processed, whether the promises are fulfilled or rejected.

0 comments on commit 4ef13e9

Please sign in to comment.