#2795
Medium JavaScript Parallel execution of promises for individual results retrieval
87.7% acceptance
Mar 31, 2026
16
5
Given an array functions, return a promise promise. functions is an array of functions that return promises fnPromise. Each fnPromise can be resolved or rejected.
If fnPromise is resolved:
obj = { status: "fulfilled", value: resolved value}
If fnPromise is rejected:
obj = { status: "rejected", reason: reason of rejection (catched error message)}
The promise should resolve with an array of these objects obj. Each obj in the array should correspond to the promises in the original array function, maintaining the same order.
Try to implement it without using the built-in method Promise.allSettled().
Solution
TypeScript
Time O(1)
Space O(1)
type FulfilledObj = {
status: "fulfilled";
value: string;
};
type RejectedObj = {
status: "rejected";
reason: string;
};
type Obj = FulfilledObj | RejectedObj;
function promiseAllSettled(functions: Function[]): Promise<Obj[]> {
return new Promise((resolve) => {
const results: Obj[] = new Array(functions.length);
let count = 0;
functions.forEach((fn, i) => {
fn()
.then((value: string) => {
results[i] = { status: "fulfilled", value };
})
.catch((reason: string) => {
results[i] = { status: "rejected", reason };
})
.finally(() => {
if (++count === functions.length) resolve(results);
});
});
});
}
/**
* const functions = [
* () => new Promise(resolve => setTimeout(() => resolve(15), 100))
* ]
* const time = performance.now()
*
* const promise = promiseAllSettled(functions);
*
* promise.then(res => {
* const out = {t: Math.floor(performance.now() - time), values: res}
* console.log(out) // {"t":100,"values":[{"status":"fulfilled","value":15}]}
* })
*/