Closed nairihar closed 4 years ago
Hi there, could you please help me to understand this code?
function myPromiseRace(promiseArr) { return new Promise(function(resolve, reject) { var isTaskCompleted = false; for(let i = 0; i < promiseArr.length; i++) { promiseArr[i] .then((result) => { if(!isTaskCompleted) { isTaskCompleted = true; resolve(result); } }, errorMsg => { if(!isTaskCompleted) { isTaskCompleted = true; reject(errorMsg); } }); } }) } var p1 = new Promise(function(resolve, reject) { reject("error"); console.log('reject') }) var p2 = new Promise(function(resolve, reject) { resolve("success"); console.log('resolve') }) myPromiseRace([p1, p2]) .then(a => console.log(a)) .catch(b => console.log(b))
This returns:
reject resolve error
If I use catch instead of the second argument I will get a different result, why?
promiseArr[i] .then((result) => { if(!isTaskCompleted) { isTaskCompleted = true; resolve(result); } }).catch(errorMsg => { if(!isTaskCompleted) { isTaskCompleted = true; reject(errorMsg); } });
reject resolve success
https://blog.insiderattack.net/promises-next-ticks-and-immediates-nodejs-event-loop-part-3-9226cbe7a6aa
Hi there, could you please help me to understand this code?
This returns:
If I use catch instead of the second argument I will get a different result, why?