Home > Web Front-end > JS Tutorial > How Do Chained Promises Handle and Propagate Rejections?

How Do Chained Promises Handle and Propagate Rejections?

Linda Hamilton
Release: 2024-12-09 07:11:07
Original
999 people have browsed it

How Do Chained Promises Handle and Propagate Rejections?

Chained Promises not Passing Rejection

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template