Explain how Promise.all() works.

Explain how Promise.all() works.

Promise.all() is a JavaScript method that takes an array of promises as input and returns a single promise that resolves when all of the input promises have resolved, or rejects if any of the input promises are rejected. It is useful for aggregating the results of multiple promises.

It is typically used when there are multiple related asynchronous tasks that the overall code relies on to work successfully — all of which we want to fulfill before the code execution continues.

Code Example of Promise.all()

// Promises Mock
const p1 = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve("p1");
        }, 3000);
    });
};

const p2 = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve("p2");
            // reject("p2");
        }, 1000);
    });
};

const p3 = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve("p3");
        }, 2000);
    });
};

Promise.all([p1(), p2(), p3()])
    .then((values) => console.log(values))
    .catch((err) => console.error(err));

//Output:
// In case all promises resolves ✅: [p1, p2, p3]
// In case p2 fails ❌: p2

Internal Workings of Promise.all()

Promise.all() then starts an internal loop that iterates over the input promises. For each promise in the array, Promise.all() checks the status of the promise. If the promise has resolved, Promise.all() adds the result of the promise to an array. If the promise has rejected, Promise.all() rejects the new promise.

Polyfill for Promise.all()

const promiseAll = (promises) => {
    const results = [];
    let count = 0;

    return new Promise((resolve, reject) => {
        promises.forEach((task, i) => {
            task
                .then((val) => {
                    count++;
                    results[i] = val;
                })
                .catch((err) => {
                    reject(err);
                })
                .finally(() => {
                    if (count >= promises.length) {
                        resolve(results);
                    }
                });
        });
    });
};

🗃️ Resources

Checkout more questions in the series: https://blog.prateekbudhiraja.in/series/frontend-interview