Skip to main content
Back to problems
#2721
Medium JavaScript

Execute asynchronous functions in parallel

78.4% acceptance
Mar 2, 2026
260
48
Given an array of asynchronous functions functions, return a new promise promise. Each function in the array accepts no arguments and returns a promise. All the promises should be executed in parallel. promise resolves: When all the promises returned from functions were resolved successfully in parallel. The resolved value of promise should be an array of all the resolved values of promises in the same order as they were in the functions. The promise should resolve when all the asynchronous functions in the array have completed execution in parallel. promise rejects: When any of the promises returned from functions were rejected. promise should also reject with the reason of the first rejection. Please solve it without using the built-in Promise.all function.

Solution

TypeScript
Time O(1)
Space O(1)
LeetCode
solution.ts
type Fn<T> = () => Promise<T>;

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

/**
 * const promise = promiseAll([() => new Promise(res => res(42))])
 * promise.then(console.log); // [42]
 */