The task is to implement Promise.all()
The boilerplate code
function all(promises) {
// your code here
}
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'));
}
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;
If the array is empty
if (total === 0) {
resolve([]);
return;
}
Loop through each promise and remember its index
promises.forEach((promise, index) => {
If it's already a promise, use it. If it's a value, convert to a promise
Promise.resolve(promise)
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);
}
}
As soon as any promise rejects, the return promise rejects
.catch(err => {
reject(err);
});
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);
})
})
})
}
That's all folks!
Top comments (0)