then / promise

Bare bones Promises/A+ implementation
https://www.promisejs.org
MIT License
2.58k stars 312 forks source link

Catch works earlier if I pass reject as second callback #164

Closed nairihar closed 4 years ago

nairihar commented 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
nairihar commented 4 years ago

https://blog.insiderattack.net/promises-next-ticks-and-immediates-nodejs-event-loop-part-3-9226cbe7a6aa