Implement Promise.all

Promise.all

The Promise.all() method returns a single Promise that resolves when all of the promises passed as an iterable have resolved or when the iterable contains no promises. It rejects with the reason of the first promise that rejects.

Question

Write a function newPromiseAll which takes an array of Promises as an argument, and retuns a promise, which if resolved, returns the result of each promise in an array, or an error catch block, if one of the promises is rejected.

newPromiseAll(promises)
.then(results => {
})
.catch(e => {
})

Thought process Pseudocode

  1. For the sake of simplicity we will create a method task which will create a promise and resolve it in some time x.
function task(time) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve(time);
}, time);
});
}
  1. Since the order of the results array is important, we will chain each promise resolution to the next one
  2. A simple forEach iterator can be used, and we need to keep track of the index of the parent array
  3. When the number of promises resolved is equal to the length of the task array we will resolve the overall results array.

Solution

function task(time) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve(time);
}, time);
});
}
const taskList = [task(1000), task(5000), task(3000)];
// returns promise with results in an array
function myPromiseAll(taskList) {
const results = []
let promisesCompleted = 0;
return new Promise((resolve, reject) => {
taskList.forEach((promise, index) => {
promise.then((val) => {
results[index] = val;
promisesCompleted += 1;
if (promisesCompleted === taskList.length) {
resolve(results)
}
})
.catch(error => {
reject(error)
})
})
});
}
myPromiseAll(taskList)
.then(results => {
console.log("got results", results)
})
.catch(console.error)

Caveat

Promise.all will fail if even one of the promises fail. The order of the results array is maintained and is equal to the task list.