Promise.all() is a method in JavaScript that takes an array of promises and returns a single Promise that resolves when all of the promises in the array have resolved, or rejects when any of the input's promises rejects, with this first rejection reason.
Here's a basic example:
const p1 = new Promise(function (resolve, reject) {
setTimeout(() => {
resolve("result 1")
}, 3000)
})
const p2 = new Promise(function (resolve, reject) {
setTimeout(() => {
resolve("result 2")
}, 1000)
})
const p3 = new Promise(function (resolve, reject) {
setTimeout(() => {
resolve("result 3")
}, 0)
})
Promise.all([p1, p2, p3])
.then(response => console.log('Response is ', response))
.catch(e => console.log(e));
// output - Response is ['result 1', 'result 2', 'result 3']
In this example, Promise.all() waits for all three promises to resolve, and then it resolves itself with an array containing the resolved values of all three promises. If any of the promises are rejected, the Promise.all() call immediately rejects with the reason of the first rejected promise.
Custom implementation for Promise.all
let's start creating our custom promise.all functions lets name it as customAll.
Step 1
As we discussed in starting, promise.all accept an array and return a promise so we will start with this.
Promise.customAll = function (promiseList) {
return new Promise(resolve, reject){
// code ...
}
}
Step 2
we will create an array named results for storing response.
Promise.customAll = function (promiseList) {
let results = [];
return new Promise(resolve, reject) {
// code ...
}
}
step 3
We will iterate input array and resolve the promise using Promise.resolve().
Note - we are manually resolving input using Promise.resolve() because Promise.all can also accept normal values as input not necessarily promise.
In case we will not manually resolve, it will throw an error ".then is not a function" for non promise values
Here we will consider three cases
If promise is resolved we will store the result in results array with respective index and increment a count variable.
If promise will be rejected we will reject the returning promise with error.
If all the promises are passed in this case count will be equal to promiseList.length (input), and we will resolve the returning promise.
In code we have only two cases one for success and other for error.
Promise.customAll = function (promiseList) {
let results = [];
let count = 0;
return new Promise((resolve, reject) => {
promiseList.forEach((promsie,index) => {
Promise.resolve(promsie)
.then(response => {
results[index] = response;
count++;
if (count == promiseList.length) {
resolve(results);
}
})
.catch(error => {
reject(error);
})
})
});
}
Its time to test are customAll function.
Promise.customAll([p1, p2, p3])
.then(response => console.log('Response is ', response))
.catch(e => console.log(e));
// output - Response is ['result 1', 'result 2', 'result 3']
You can test this code for error cases.
Top comments (0)