What do you think will be result of this code below?
const milliseconds = [1000,2000,3000,5000,10000];
const get = (milliseconds) =>{
return new Promise((resolve,reject)=>{
setTimeout(function(){
console.log(`Inside set time out ${milliseconds}`)
if(milliseconds < 5000){
resolve('Got milliseconds less than 5000')
}
reject('Can not have milliseconds more than 5000')
}, milliseconds);
})
}
const promises = [];
Promise.all( milliseconds.map(msec=>{
return get(msec)
})).then(response=> console.log(response)).catch(err=> console.error(err))
Many people will assume that it will not run all the promises. That it will stop executing after the third index. But the fact is promise.all runs parallel so it will map through all the array. However, since one of them is rejecting, it will reject all other promises as well. The console will look like this.
Inside set time out 1000
Inside set time out 2000
Inside set time out 3000
Inside set time out 5000
Can not have seconds more than 5000 // only rejected console is displayed
Inside set time out 10000
I hope this post was helpful to you. If you like my post, follow me @twitter/andramazo.