Skip to content

2795. Parallel Execution of Promises for Individual Results Retrieval

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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[] = Array.from({ length: functions.length });
    let count = 0;
    functions.forEach((fn, index) => {
      fn()
        .then((value) => {
          results[index] = { status: 'fulfilled', value };
        })
        .catch((reason) => {
          results[index] = { status: 'rejected', reason };
        })
        .finally(() => {
          if (++count === functions.length) {
            resolve(results);
          }
        });
    });
  });
}