Chained Promises Not Passing on Rejection
Despite their intended dependency on a previous promise, chained promises may fail to propagate errors. This behavior can be puzzling, but is rooted in the nature of Promises/A.
Misconception: Chain Dependency
The misconception is that each then implies dependency on the preceding promise's successful resolution. However, this is not the case.
Promise Chaining
In promise chaining, the result of the callback function in a then becomes the resolution of the subsequent promise. Therefore:
Handling Rejection
Errors thrown or rejected promises in a then callback trigger the next promise's catch or error callback. However, if the error is handled within the callback, the chain proceeds as if the promise was successfully resolved.
Example:
Consider the following code:
let promise1 = Promise.resolve(42); let promise2 = promise1.then( (value) => value * 2, (err) => { console.error('Error in promise1:', err); // Handle the error (e.g., return a new promise) } ); promise2.then((value) => console.log('Value from promise2:', value));
In this example, if promise1 is rejected, its error handler logs the error and then returns a default value. This allows promise2 to proceed as if it had received a successful response from promise1.
Application to Database Updates
In your database update example, the error in db.query will be handled in its then callback and a default value will be provided. This allows the subsequent then callbacks to proceed and still perform the database updates, even though db.query failed.
Best Practices
To ensure consistent error handling, consider the following best practices:
The above is the detailed content of Why Do Chained Promises Sometimes Ignore Rejections?. For more information, please follow other related articles on the PHP Chinese website!