【问题标题】:nodejs+Q promises: no Reference Exception in the fulfillment handlenodejs+Q 承诺:实现句柄中没有引用异常
【发布时间】:2016-09-12 03:53:23
【问题描述】:

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

由于“不存在”部分而没有语法/参考或任何其他错误。 完成句柄之外的相同错误会抛出应有的错误。

我在 Ubuntu 上使用 nodejs 4.4.4。

【问题讨论】:

  • 同样适用于 nodejs 6.1.0
  • 任何帮助或评论?这个问题使我所有的拼写错误都变得至关重要 - 因为我的项目现在非常复杂 - 有许多 aync 路径和长循环 - 应用程序内的一些执行路径失败,没有错误消息。跟踪他们需要很长时间......

标签: node.js promise nullreferenceexception


【解决方案1】:

好的,我找到了这个:

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 is not defined

【讨论】:

    猜你喜欢
    • 2014-01-04
    • 2015-10-24
    • 1970-01-01
    • 2017-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-04
    • 1970-01-01
    相关资源
    最近更新 更多