At the end I included two example promises to check that the code works and it does work:
async function slower(arr: Promise<any> []): Promise<[number ,any] | undefined | any[]> {
/* here we check if one is rejected in the question i solved
we have to return or print something if one of the two
promises has rejected its just an extra
*/
let firstisresolved = false;
let secondisresolved = false;
try {
await arr[0].then(function(){
firstisresolved = true;
});
await arr[1].then(function(){
secondisresolved = true;
});
} catch {
console.log("something went bad");
}
/* we get an array of tow promises and we basically check which
one is faster-using promise.race()() and promise.all
*/
if (!(secondisresolved && firstisresolved )) {
console.log("there is one promise got rejected");
return;
} else {
let num =1;
try {
/* here its very important to run promise.race() before
running promise.all() because if you run all and then
race the promises would be already done so you it will
return the first one any way so remeber to run
promise.race() before promise.all()
*/
let a = await Promise.race(arr);
let b = await Promise.all(arr);
if(a === b[0]){
num = 0;
}
// console.log(num);
// console.log(a);
let c = [num,a]
return c;
} catch(err) {
console.log("there is a problem")
}
}
}
const promise1 = new Promise((resolve, reject) => {
setTimeout(resolve, 5000, 'one');
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(resolve, 6000, 'two');
});
console.log(slower([promise1,promise2]));