5-min frontend interview prep
In last Blog we learnt Promise.all() , now let's get into Promise.any()
It's basically counterintuitive right just by seeing words , yes you heard it right
Promise.any() also takes an iterable of promise objects, it will return a promise that fullfills as soon as any of the promise in the iterable fulfills with a value of fullfilled promise , if no promise in iterable fullfills , then returned promise is rejected with an error
wait what?
Let's break this
1) it takes array of promises and returns a new promise
2) returned promise is resolved as soon as any of input promise resolves
3) if all of input promises rejected then returned promise is rejected with the array of all input promises
Okay now let's implement
const any = function(promiseArray){
const promiseErrors = new Array(promisesArray.length)
let counter = 0;
// returns a new promise
return new Promise((res,rej)=>{
promiseArray.forEach((promise)=>{
Promise.res(promise)
.then(res)
.catch((err)=>{
// error
promiseErrors[counter] = err;
counter++;
if(counter === promiseArray.length){
// all promises rejected , reject parent promise
rej(promiseErrors)
}
})
})
})
}
To make it short consider Promise.any() is nothing but it takes an array of promises and it will return a promise which will resolve if any of the promise in the array of promise resolves or else it will reject with the aggregated errors which are nothing but group of individual errors