What is Promise.all
5 minute frontend interview prep
Promise.all() will accept an array of promises and returns a promise that resolves when all the promises in the array are fullfilled or when the iterable contains no promises . it rejects when any one of those promise rejects ,
it’s like the proverb building reputation takes years but breaking can take one bad move , now Let's implement promise.all()
const promiseAll = function(tasks){
// for storing results
let results = [];
// to track how many promises are completed
let totalPromise = 0
// returns a new promise
return new Promise((res,rej)=>{
tasks.forEach((promise,index)) =>{
// if promises pass
promise.then((val)=>{
// store it in results in order
results[index] = val;
totalPromise+=1
// if all promises aree completed then
if(totalPromises === tasks.length){
res(results)
}
}
// if promise fails
.catch(err=> rej(err))
}
}
)
}
This is basic implementation of promise.all() , always remember it will return a promise which will resolve if all promises in the array are fullfilled and it will reject or gives an error even one promise is rejected