小编典典

蓝鸟Promise的异步异常处理

node.js

什么是处理这种情况的最佳方法。我处于受控环境中,所以我不想崩溃。

var Promise = require('bluebird');

function getPromise(){
    return new Promise(function(done, reject){
        setTimeout(function(){
                throw new Error("AJAJAJA");
        }, 500);
    });
}

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);
    });

从setTimeout内抛出时,我们将始终获得:

$ node bluebird.js

c:\blp\rplus\bbcode\scratchboard\bluebird.js:6
                throw new Error("AJAJAJA");
                      ^
Error: AJAJAJA
    at null._onTimeout (c:\blp\rplus\bbcode\scratchboard\bluebird.js:6:23)
    at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)

如果抛出发生在setTimeout之前,那么bluebirds catch将捕获它:

var Promise = require('bluebird');

function getPromise(){

    return new Promise(function(done, reject){
        throw new Error("Oh no!");
        setTimeout(function(){
            console.log("hihihihi")
        }, 500);
    });
}

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);
    });

结果是:

$ node bluebird.js
Error [Error: Oh no!]

很棒-但是如何在节点或浏览器中处理这种性质的恶意异步回调。


阅读 306

收藏
2020-07-07

共1个答案

小编典典

承诺不是,它们不会捕获异步回调中的异常。你就是做不到。

然而诺言来捕捉从内抛出的异常then/ catch/ Promise构造函数的回调。所以用

function getPromise(){
    return new Promise(function(done, reject){
        setTimeout(done, 500);
    }).then(function() {
        console.log("hihihihi");
        throw new Error("Oh no!");
    });
}

(或仅Promise.delay)以获得所需的行为。永远不要抛出自定义(非承诺)异步回调,总是拒绝周围的承诺。使用try- catch它是否真正需要。

2020-07-07