tonitone120
tonitone120

Reputation: 2300

How does a Promise.prototype.catch, at the end of a .then chain, receive rejected promises?

I know that if a .then receives a rejected promise, and it has no handler for it, the new promise .then returns becomes the state of the promise .then received (source).

In fact, my intuition would tell me this is how .catch, appended at the end of a .then chain, receives a promise (when all the .thens have no rejection handlers). Each .then is called, returning duplicates of the original failed promise.

Additionally, when I'm reading this article I get the impression that when a promise's executor or a .then's callback simply returns an error object, it'll somehow 'jump' and return this error object to the nearest rejection handler (surely this could be a regular .then that has a callback as a second argument or a .catch()). Are both ideas right here?

Upvotes: 1

Views: 63

Answers (1)

Bergi
Bergi

Reputation: 664548

When I'm reading this article I get the impression that it'll somehow 'jump'

No, that's misleading. Your first intuition was right. When the promise that .then(…) was called on is rejected, the promise that .then(…) returned will also get rejected, and so on down the chain. This even takes some time actually (and other promise handlers might run in between).

Of course, the logical execution flow skips the then handlers on all the rejected promise and the next thing from this chain that will run is a catch (or then) rejection handler, so you might consider it to "jump", but that really an analogy only and is actually implemented by rejecting each promise along the chain.

You get actual jumps of flow control when using promises with async/await in try/catch blocks.

Upvotes: 1

Related Questions