The task is to implement the promise.allSettled method.
The boilerplate code
function allSettled(promises) {
// your code here
}
Promise.allSettled receives an array of promises, waits for all of them to settle and never rejects.
Promise.allSettled returns a promise
return new Promise((resolve) => {
}
Store the final output objects, and count how many promises have finished
const results = [];
let completed = 0;
If the arguments are not iterable
if(!Array.isArray(promises)) {
throw new TypeError("Argument must be iterable")
}
If there are no promises
if (promises.length === 0) {
resolve(results);
return;
}
Loop through each promise, store the index to preserve order and store results in their correct position.
promises.forEach((promise, index) => {
If the input is already a promise, use it. If it's a value, convert it to a promise.
Promise.resolve(promise)
When a promise resolves, store it in the correct index
.then(value => {
results[index] = {
status: 'fulfilled',
value
};
})
When a promise is rejected, it should be captured but not propagated.
.catch(reason => {
results[index] = {
status: 'rejected',
reason
};
})
When all promises are done, resolve the final array
.finally(() => {
completed++;
if (completed === promises.length) {
resolve(results);
}
});
The final code
function allSettled(promises) {
// your code here
return new Promise((resolve) => {
if(!Array.isArray(promises)) {
throw new TypeError("Argument must be iterable")
}
const results = [];
let completed = 0;
if(promises.length === 0) {
resolve(results);
return;
}
promises.forEach((promise, index) => {
Promise.resolve(promise)
.then(value => {
results[index] = {
status: 'fulfilled',
value
}
})
.catch(reason => {
results[index] = {
status: 'rejected',
reason
}
})
.finally(() => {
completed++;
if(completed === promises.length) {
resolve(results);
}
})
})
})
}
That's all folks!
Top comments (0)