首页  >  文章  >  web前端  >  如何使用 Bluebird Promise 处理异步回调中未处理的异常?

如何使用 Bluebird Promise 处理异步回调中未处理的异常?

DDD
DDD原创
2024-10-26 16:39:30947浏览

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

使用 Bluebird Promises 进行异步异常处理

问:如何使用 Bluebird Promises 处理异步回调中未处理的异常?

与域不同,Bluebird Promise 本质上不会捕获异步回调抛出的异常。

A:使用 Promise 构造函数或 then() 闭包来处理异常

要捕获异步回调中的异常,请将回调包装在 Promise 构造函数或 then() 闭包中:

<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>

避免抛出自定义异步回调

从不直接在自定义异步回调中抛出异常(在 Promise 回调之外)。相反,拒绝周围的 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>

示例

使用 Promise 构造函数:

<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>

输出:

Error [Error: Oh no!]

此方法可确保捕获并适当处理异常,从而防止应用程序崩溃。

以上是如何使用 Bluebird Promise 处理异步回调中未处理的异常?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn