Home > Web Front-end > JS Tutorial > body text

How do you handle unhandled exceptions in asynchronous callbacks with Bluebird promises?

DDD
Release: 2024-10-26 16:39:30
Original
1057 people have browsed it

How do you handle unhandled exceptions in asynchronous callbacks with Bluebird promises?

Asynchronous Exception Handling with Bluebird Promises

Q: How to handle unhandled exceptions in asynchronous callbacks with Bluebird promises?

Bluebird promises do not inherently catch exceptions thrown from asynchronous callbacks, unlike domains.

A: Use Promise Constructors or then() Closures to Handle Exceptions

To catch exceptions in async callbacks, wrap the callback in a promise constructor or then() closure:

<code class="javascript">function getPromise(){
    return new Promise(function(done, reject){
        setTimeout(function(){
            throw new Error("AJAJAJA");
        }, 500);
    }).then(function() {
        console.log("hihihihi");
        throw new Error("Oh no!");
    });
}</code>
Copy after login

Avoid Throwing in Custom Async Callbacks

Never throw exceptions directly in custom async callbacks (outside of promise callbacks). Instead, reject the surrounding promise:

<code class="javascript">function getPromise(){
    return new Promise(function(done, reject){
        setTimeout(done, 500);
    }).then(function() {
        console.log("hihihihi");
        reject(new Error("Oh no!"));
    });
}</code>
Copy after login

Example

Using a promise constructor:

<code class="javascript">var p = getPromise();
    p.then(function(){
        console.log("Yay");
    }).error(function(e){
        console.log("Rejected",e);
    }).catch(Error, function(e){
        console.log("Error",e);
    }).catch(function(e){
        console.log("Unknown", e);
    });</code>
Copy after login

Output:

Error [Error: Oh no!]
Copy after login

This approach ensures that exceptions are caught and handled appropriately, preventing the application from crashing.

The above is the detailed content of How do you handle unhandled exceptions in asynchronous callbacks with Bluebird promises?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template