2721. Execute Asynchronous Functions in Parallel

2721. Execute Asynchronous Functions in Parallel

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.

/**
 * @param {Array<Function>} functions
 * @return {Promise<any>}
 */
var promiseAll = function (functions) {
  return new Promise(function (resolve, reject) {
    const result = [];
    let times = 0;
    for (let i = 0; i < functions.length; i++) {
      functions[i]()
        .then(res => {
          times++; // 當每一次 promise 被完成之後就+1
          result[i] = res;
          if (times === functions.length) {
            // 當完成次數等於 function 個數就 resolve
            resolve(result);
          }
        })
        .catch(err => {
          reject(err); // 當有 error 出現就 reject
        });
    }
  });
};