nodejs + Q promises:在履行句柄

时间:2016-05-16 11:12:30

标签: node.js promise nullreferenceexception

我是nodejs的新手,试图编写第一个更大的项目。不幸的是,当我在Q fullfilment句柄中犯了一个错误时,我一直坚持使用nodejs退出而没有错误。

示例:

var Q = require('q');
    function test1() {
        var deferred = Q.defer();
        deferred.resolve();
        return(deferred.promise);
}

console.log("Start");
test1() 
.then (function(ret) {
    imnotexisting;   //this should be shown as Reference Exception
    console.log("OK");
}, function(err) {
    console.log("FAIL");
});
console.log("Stop");

'

输出将是:

Start
Stop

没有语法/引用或任何其他错误,因为" imnotexisting"部分。 fullfilment句柄之外的相同错误会引发错误。

我在Ubuntu上使用nodejs 4.4.4。

1 个答案:

答案 0 :(得分:0)

好的,我发现了这个:

One sometimes-unintuive aspect of promises is that if you throw an exception in the fulfillment handler, it will not be caught by the error handler.
(...)
To see why this is, consider the parallel between promises and try/catch. We are try-ing to execute foo(): the error handler represents a catch for foo(), while the fulfillment handler represents code that happens after the try/catch block. That code then needs its own try/catch block.

我们需要添加.fail部分,如下所示:

    var Q = require('q');
    function test1() {
        var deferred = Q.defer();
        deferred.resolve();
        return(deferred.promise);
}

console.log("Start");
test1() 
.then (function(ret) {
    imnotexisting;
    console.log("OK");
}, function(err) {
    console.log("FAIL");
})
.fail (function(err) {
    console.log("Error: "+err);
});
console.log("Stop");

结果是: 开始 停止 错误:ReferenceError:未定义imnotexisting