使用bluebird承诺进行异步异常处理

j03*_*03m 12 javascript asynchronous node.js promise bluebird

处理此方案的最佳方法是什么.我处于受控环境中,我不想崩溃.

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);
    });
Run Code Online (Sandbox Code Playgroud)

从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)
Run Code Online (Sandbox Code Playgroud)

如果抛出发生在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);
    });
Run Code Online (Sandbox Code Playgroud)

结果是:

$ node bluebird.js
Error [Error: Oh no!]
Run Code Online (Sandbox Code Playgroud)

哪个好 - 但是如何在节点或浏览器中处理这种性质的流氓异步回调.

Ber*_*rgi 15

Promise不是,它们不会捕获异步回调的异常.你不能这样做.

但是,Promise会捕获从then/ catch/ Promise构造函数回调中抛出的异常.所以使用

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

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