-1

I understand that promise 3 is rejected because it resolves to an already rejected promise (promise 2), but how does promise 3 get to reject promise 4?, what is going on behind the scenes?

 Promise.resolve(6) // promise 1
 .then(function(data) {
    console.log('then 1:' + data);
    return Promise.reject(new Error('ups - rejected'));
 }) // promise 2
 .then(function (data) {
    console.log('then 2:' + data);
    return data + 1; 
 }) // promise 3
.then(function (data) {
    console.log('then 3:' + data);
    return data + 1; 
 }) // promise 4
 .catch(function(error) { // catch of promise 4
  console.log(error);
 });
  • **Comments have been [moved to chat](https://chat.stackoverflow.com/rooms/252642/discussion-on-question-by-coder23-how-can-an-intermediate-promise-be-rejected); please do not continue the discussion here.** Before posting a comment below this one, please review the [purposes of comments](/help/privileges/comment). Comments that do not request clarification or suggest improvements usually belong as an [answer](/help/how-to-answer), on [meta], or in [chat]. Comments continuing discussion may be removed. – Samuel Liew Mar 21 '23 at 01:59
  • 1
    Does this answer your question? [Why is it possible to use only a catch() at the end?](https://stackoverflow.com/questions/75778431/why-is-it-possible-to-use-only-a-catch-at-the-end) – Jeff Bowman Mar 22 '23 at 23:48

1 Answers1

0

Recall that each then in the chain defines a Promise, and they are processed in order. In the "happy case" there are no errors and the result of each onFulfilled handler is passed as an argument to the next Promise.

Similarly, if an error occurs – either by an explicit Promise.reject or a throw – then the error object is passed as an argument to the onRejected handler of the next Promise.

If an onRejected handler returns a value then it will be passed onto the next onFulfilled handler, i.e. the error is regarded as "taken care of"; if, however, it rejects or re-throws the error then that will be passed to the next onRejected handler.

The link you've provided clarifies that the default onRejected handler is function ((x) => { throw x; }) – that is, if you don't define your own handler then any error from earlier in the chain is re-thrown. So, the default behaviour is that the error is just passed down the chain until it gets to the end.

Recall that .catch(handler) is just syntactic sugar for .then(undefined, handler). There's nothing special about it being at the end – you can put .catch(..) handlers in the middle of the chain – but if some Promise in the chain throws an unhandled error then you see the familiar Uncaught (in Promise) message / error in the console.

motto
  • 2,888
  • 2
  • 2
  • 14