AlgoDaily

Implement Promise.all

Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.

Question

According to the MDN docs, the Promise.all() method "takes an iterable of promises as an input, and returns a single Promise that resolves to an array of the results of the input promises". It is useful when there is a collection of promises that you need to resolve prior to some other code execution work that neeeds to be done.

Here's an example of it being used:

const promise1 = Promise.resolve(5);
const promise2 = 2022;
const promise3 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("foo");
  }, 100);
});

Promise.all([p1, p2, p3]).then((values) => {
  console.log(values);
  // will print [5, 2022, "foo"]
});

One caveat to note is that it will reject if any of the input promises are rejected. It will reject with the first rejection message or error. This is different than Promise.allSettled. The allSettled sibling method waits for its input promises to all complete and returns the final result of each.

cover

```js
Promise.all = (promises) => {
  return new Promise((resolve, reject) => {
    const results = []; // Array to store the results of the promises

    // TODO: Check if the promises array is empty, and if so, resolve with the empty results array

    let pending = promises.length; // Counter for the number of pending promises

    promises.forEach((promise, idx) => {
      // TODO: Resolve each promise and store its result in the results array
      // If all promises are resolved, call resolve with the results array
      // If any promise is rejected, call reject
    });
  });
};
```

Solution

Solution

Starting the Function
Step 1: Creating the Structure

We begin by defining our function and returning a new promise. This sets the stage for handling multiple promises.

Promise.all = (promises) => {
  return new Promise((resolve, reject) => {
    // This is where the magic happens!
  });
};
Handling Edge Cases
Step 2: Setting up the Results Array

Before we do anything else, we create an empty array to hold our results.

const results = [];
Step 3: No Promises Edge Case

If there are no promises in the input array, we immediately resolve to the empty results array.

if (!promises.length) {
  resolve(results);
  return;
}
Resolving the Promises
Step 4: Tracking Pending Promises

We'll set up a counter to keep track of the pending promises. This helps us know when all promises are resolved.

let pending = promises.length;
Step 5: Iterating Through the Promises

We'll iterate through the promises, resolving each one.

promises.forEach((promise, idx) => {
  // We'll be resolving each promise here
});
Step 6: Resolving Each Promise

Inside our loop, we call Promise.resolve on each promise. This takes care of converting non-promise values to promises.

Promise.resolve(promise).then((value) => {
  // We'll handle the resolved value here
}, reject);
Step 7: Adding Values to Results

When a promise is resolved, we add its value to the results array at the corresponding index. This ensures the order of the results matches the input promises.

results[idx] = value;
Step 8: Checking for Completion

We decrement our pending counter and check if it has reached zero. If so, we know all promises are resolved, and we can resolve our main promise with the results array.

pending--;
if (pending === 0) {
  resolve(results);
}
Final Code

Putting it all together, our final implementation looks like this:

Promise.all = (promises) => {
  return new Promise((resolve, reject) => {
    const results = [];
    if (!promises.length) {
      resolve(results);
      return;
    }
    let pending = promises.length;
    promises.forEach((promise, idx) => {
      Promise.resolve(promise).then((value) => {
        results[idx] = value;
        pending--;
        if (pending === 0) {
          resolve(results);
        }
      }, reject);
    });
  });
};

This step-by-step breakdown of the Promise.all implementation allows us to appreciate the intricacy of asynchronous programming. By understanding how to build such a method ourselves, we gain valuable insight into the nature of promises and how they are handled in JavaScript.

One Pager Cheat Sheet

One Pager Cheat Sheet

  • Promise.all() is used to take an iterable of promises as an input, wait for them to resolve, and return a single Promise that resolves to an array of the results, but will reject with the first rejection message or error if any of the input promises are rejected.
  • We can implement an all function that takes an array of promises and returns a Promise that resolves to an array of return values from the input.
Open interactive view →