DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 92

The task is to implement Promise.all()

The boilerplate code

function all(promises) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

Promise.all takes an array of promises and returns one promise. When all promises resolve, it resolves with an array of results and maintains the original order.

Validate if the argument is iterable

return new Promise((resolve, reject) => { 
if (!Array.isArray(promises)) {
  return reject(new TypeError('Argument must be an array'));
}
Enter fullscreen mode Exit fullscreen mode

Store the resolved values, count how many promises have been resolved, and the total number of promises.

const results = [];
let completed = 0;
const total = promises.length;
Enter fullscreen mode Exit fullscreen mode

If the array is empty

if (total === 0) {
  resolve([]);
  return;
}

Enter fullscreen mode Exit fullscreen mode

Loop through each promise and remember its index

promises.forEach((promise, index) => {
Enter fullscreen mode Exit fullscreen mode

If it's already a promise, use it. If it's a value, convert to a promise

Promise.resolve(promise)
Enter fullscreen mode Exit fullscreen mode

Store the result at the correct index, increase the completion count and resolve final promise when all are done

.then(value => {
  results[index] = value;
  completed++;

  if (completed === total) {
    resolve(results);
  }
}
Enter fullscreen mode Exit fullscreen mode

As soon as any promise rejects, the return promise rejects

.catch(err => {
  reject(err);
});
Enter fullscreen mode Exit fullscreen mode

The final code

function all(promises) {
  // your code here
  return new Promise((resolve, reject) => {
    if(!Array.isArray(promises)) {
      return reject(new TypeError('Argument must be an array'))
    }

    const results = [];
    let completed = 0;
    const total = promises.length;

    if(total === 0) {
      resolve([]);
      return;
    }
    promises.forEach((promise, index) => {
      Promise.resolve(promise)
      .then(value => {
        results[index] = value;
        completed++;

        if(completed === total) {
          resolve(results);
        }
      })
      .catch(err => {
        reject(err);
      })
    })
  })
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)