Akhil-Sharma02
Akhil-Sharma02

Reputation: 93

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?

Upvotes: 0

Views: 40

Answers (2)

Reza
Reza

Reputation: 19843

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 thens after catch

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370639

.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 .catchs at the very end of a Promise chain - it makes the control flow easier to understand.

Upvotes: 2

Related Questions