how p3 is undefined here ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

how p3 is undefined here ?

let p1 = new Promise((res, rej) => { setTimeout(res, 500, "p1"); }); let p2 = new Promise((res, rej) => { setTimeout(res, 500, "p2"); }); let p3 = new Promise((res, rej) => { setTimeout(rej, 500, "p3"); }); let result = Promise.all([ p1.catch(() => {}), p2.catch(() => {}), p3.catch(() => {}), ]); result .then((data) => { data.forEach((i) => console.log(i)); }) .catch((err) => console.log('error' + err));

29th Jan 2024, 1:15 PM
susi
susi - avatar
3 Answers
+ 1
Because you used “rej” in p3, which would return null
29th Jan 2024, 10:36 PM
Defying Gravity
Defying Gravity - avatar
+ 1
you using Promise.all and catching the errors in it and discarding them. What will the last line in your code catch? Also Promise.all exits when it catches a rej. if your rej is in p1, none of the res after that will be returned in the result. I would use Promise.all if I want an all or nothing result. Since you have a rej in one of your promises, I would not use it if I want to display all res and rej. you can resolve them sequentially or you can use Promise.allSettled instead https://sololearn.com/compiler-playground/W1403Y2N07kj/?ref=app
30th Jan 2024, 12:28 AM
Bob_Li
Bob_Li - avatar
0
The reason you are getting undefined is due to the callback that is passed to the p3.catch method, it returns undefined. If you want to see "p3" logged to the console then you need to pass that info to the callback and then have the callback return the info that was to it. Like so: p3.catch((data)=>data). Ref: https://javascript.info/promise-api#promise-all, https://javascript.info/promise-api#promise-allsettled
30th Jan 2024, 11:42 AM
ODLNT
ODLNT - avatar