Home >Web Front-end >JS Tutorial >How Do Errors Propagate Through JavaScript Promise Chains?
Chained Promises: Understanding Error Propagation
In a promise chain, each promise's resolution or rejection can affect subsequent promises. However, there's a common misconception that errors must always be propagated through the chain.
Promise Chain Behavior
When a promise is resolved or rejected, it triggers its then callbacks. The success or error handler can return a value or promise, which becomes the resolution of the next promise in the chain.
Error Handling in Promises
If the error handler in a promise chain does not re-throw the error or return a rejected promise, the error will not be propagated to subsequent promises. This is because the chain considers the error as handled within that promise.
Propagation vs. Error Handling
In the deferred node module example you provided, the error is not propagated to promise2 because the error handler in promise1 does not re-throw the error. By not re-throwing the error, it signals to the chain that the error has been handled. To propagate the error, you would need to modify the code as follows:
promise1.then( function(wins) { console.log('promise1 resolved'); return wins;}, function(err) { console.log('promise1 rejected'); throw err;}); // re-throw error
Re-throwing Errors and Error Handling
Re-throwing the error is analogous to passing the "error note" from John to Ginger to Bob. If Ginger handles the error (i.e., doesn't re-throw it), she can still fulfill Bob's request with a different item (e.g., a green widget). This aligns with the notion that error handling in a promise is not strictly about propagating the error, but also about mitigating its impact.
In the database example, if the initial query fails, the error handler in the first promise chain should re-throw the error to propagate it to subsequent promises. Otherwise, the chain will consider the error as handled and continue with the other insertion.
The above is the detailed content of How Do Errors Propagate Through JavaScript Promise Chains?. For more information, please follow other related articles on the PHP Chinese website!