21

What is the difference between catch and then(_,onRejected) in ES6 Promise? I just know that onRejected doesn't handle the rejected state of inner Promise.

Promise.resolve().then(() => {
    return new Promise((resolve,reject) => {
      throw new Error('Error occurs');
    }); 
},er => console.log(er)); //Chrome throws `Uncaught (in promise)`

Promise.resolve().then(() => {
    return new Promise((resolve,reject) => {
      throw new Error('Error occurs');
    }); 
}).catch(er => console.log(er)); //Error occurs
Lewis
  • 14,132
  • 12
  • 66
  • 87

2 Answers2

23

Your first piece of code wont catch the error because the error handler is in the same .then where the error is thrown


As for your question

.catch(onRejected);

is identical to

.then(null, onRejected);

not sure what

.then(_, onRejected);

would do, depends on what _ is I guess

Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
1

In the first example, your onRejected applies only to Promise.resolve(). In then(onResolved, onRejected), only one of two the function will be called, not both. Try with Promise.reject('something').then(), you'll have something printed in the console. The catch() applies to the promise you're returning so the Error is caught as expected.

Shanoor
  • 13,344
  • 2
  • 29
  • 40