In a promise chain, the resolution of a promise depends on how its error handler functions respond to a rejection. The .then() method returns a new promise for the result of the callback function. If no success or error handler is provided, the result will be passed directly to the next promise.
If the error is handled, the resulting promise will fulfill with the returned value from the error handler. To re-throw the error and propagate it down the chain, throw err instead.
In the widget shop example, when a promise in the chain receives an error, it should throw it onward to ensure that subsequent promises in the chain don't receive a success value.
In a database query chain, if an error occurs in the first query, omitting the error handler will allow the chain to continue, even though the subsequent promises may not receive meaningful values.
db.query({ parent_id: value }).then(function(query_result) { return db.put({ parent_id: query_result[0].parent_id }); }).then(function(first_value_result) { return db.put({ reference_to_first_value_id: first_value_result.id }); }.then(values_successfully_entered);
In summary, to prevent subsequent promises in a chain from receiving success values after a rejection has occurred, the error handler function should either throw the error or return a rejected promise.
The above is the detailed content of How Do Chained Promises Handle and Propagate Rejections?. For more information, please follow other related articles on the PHP Chinese website!