简体   繁体   中英

Not able to understand why this code yield this output

I am doing a react course online. In there after function chaining topic, there was an mcq to predict the output. The code is:

 function job() { return new Promise(function(resolve, reject) { reject(); }); } let promise = job(); promise.then(function() { console.log('Success 1'); }).then(function() { console.log('Success 2'); }).then(function() { console.log('Success 3'); }).catch(function() { console.log('Error 1'); }).then(function() { console.log('Success 4'); });

But why does this code yield Error 1,Success 4 as output?

.catch will result in passing a resolved Promise to the next step of the chain - unless the .catch handler itself throws. That is, given any:

.catch(someCallback)
.then(someFn);

Unless someCallback throws an error (which would result in a rejected Promise, that could be called by a .catch further down the line), no matter the situation otherwise, someFn will always run.

This is one of the reasons that many choose to put .catch s at the very end of a Promise chain - it makes the control flow easier to understand.

function job() {
  return new Promise(function(resolve, reject) {
    reject();
  });
}

let promise = job();

your promise is the result of job(), if you see your promise is rejected via reject() , it means it will go through to .catch , and since catch also return a promise, it will go to all then s after catch

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM