Reputation: 951
My question is how errors are propagated through a series of then continuations to a catch continuation.
Given
Promise.reject(new Error("some error"))
.then(v => v + 5)
.then(v => v + 15)
.catch(error => console.log(error));
After line 1 we have a rejected promise. When the continuation is invoked, .then(v => v + 5), is the original rejected promise returned as is. And the same applies for line 3. So no then continuations are run and once the catch continuation is reached we still have the same original object with the error as the result which is then passed to the catch continuation.
Is this assumption correct?
Upvotes: 0
Views: 708
Reputation: 665456
is the original rejected promise returned as is
No, when the then
method is called it doesn't know the result yet1, so it creates a new promise and returns that. That new promise is however immediately rejected with the same reason as soon as the original promise rejects. The same happens for the promise from line 3, and the final promise in line 4 is then resolved with the result of the catch
callback.
1: At least in ES6 promises, which you were asking about. Other promise implementations such as Creed make an optimisation and do indeed simply return the input promise when they now that it already is rejected.
Upvotes: 2
Reputation:
Yes, as is clear from the spec:
2.2.7. then
must return a promise.
promise2 = promise1.then(onFulfilled, onRejected);
2.2.7.4. If onRejected
is not a function [[or not specified]] and promise1
is rejected, promise2
must be rejected with the same reason as promise1
.
In other words, it is not exactly that the intermediate then
's are "skipped", or that the promise "falls through" them (although one could sort of think of it that way); rather, the promises they return are rejected with the same reason as the input promise.
By the way, it is more accurate to call these "rejections", rather than "errors" (although, the "reason" for a rejection would often be an error). And it would also be more common to call these "handlers", not "continuations".
Upvotes: 3