TobilobaCodes – LeetCode Explorer

2721. Execute Asynchronous Functions in Parallel

In this challenge, you must implement a function that accepts an array of asynchronous functions and executes them all in parallel, returning a single Promise.

📄 Problem Statement

Given an array of functions functions, each returning a Promise, return a new Promise that:

🚫 Do not use Promise.all.

💡 Example


const asyncFunc1 = () => new Promise(res => setTimeout(() => res("A"), 100));
const asyncFunc2 = () => new Promise(res => setTimeout(() => res("B"), 50));

executeFunctionsInParallel([asyncFunc1, asyncFunc2])
  .then(console.log); // ["A", "B"]

🧠 Explanation

You manually track the results and completions of each Promise. You also monitor for rejection. Once all promises are resolved, the main Promise resolves with the ordered results.

✅ Your Solution


/**
 * @param {Array<() => Promise>} functions
 * @return {Promise}
 */
var executeFunctionsInParallel = function(functions) {
    return new Promise((resolve, reject) => {
        const results = [];
        let completed = 0;
        let hasError = false;

        functions.forEach((fn, i) => {
            fn()
                .then((val) => {
                    if (hasError) return;
                    results[i] = val;
                    completed++;
                    if (completed === functions.length) {
                        resolve(results);
                    }
                })
                .catch((err) => {
                    if (!hasError) {
                        hasError = true;
                        reject(err);
                    }
                });
        });
    });
};