Skip to content

2721. Execute Asynchronous Functions in Parallel 👍

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
type Fn<T> = () => Promise<T>;

function promiseAll<T>(functions: Fn<T>[]): Promise<T[]> {
  return new Promise((resolve, reject) => {
    const ans: T[] = [];
    let resolveCount = 0;
    functions.forEach((fn, index) => {
      fn()
        .then((val) => {
          ans[index] = val;
          if (++resolveCount === functions.length) {
            resolve(ans);
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  });
}