javascript - 异步 node.js 代码(使用 Q)不写入标准错误

标签 javascript node.js asynchronous error-handling q

我在编写异步 node.js 代码时遇到了以下问题:在异步 block 中抛出的错误不会向控制台打印任何标准错误,它们只是默默地失败。

这是一个重现问题的独立工作示例,我在异步回调的外部和内部调用了一个不存在的函数:

注意//!评论

var Q = require('Q');

function asyncFunc(){
    var deferred = Q.defer();

    setTimeout(function(){
        console.log('resolving promise!');
        deferred.resolve('resolveMessage');
    },2000);

    return deferred.promise;
}

asyncFunc()
    .then(function (msg) {
        nonExisting(); // ! calling here puts no error on the console
        console.log('Promise.then entered, msg:',msg);
    });

//nonExisting(); // ! calling here results in referenceError correctly printed to the console

我正在使用 node file.js 命令从标准 Windows 命令提示符运行代码。 (我在 Windows 7 上运行 Node 0.10.32)

为什么会发生这种情况,我该如何解决这个问题?

最佳答案

这是预期的行为。

来自Q API Reference:

Since exceptions thrown in then callbacks are consumed and transformed into rejections, exceptions at the end of the chain are easy to accidentally, silently ignore.

如果您希望在链中的任何 promise 被拒绝或在解析处理程序中抛出异常时传播异常,请使用done:

asyncFunc().done(function (msg) { nonExisting(); }); //will throw an error in the next tick
process.on('uncaughtException', console.log);

您也可以将它链接到另一个 then,它的拒绝处理程序将被执行。

asyncFunc()
    .then(function (msg) {
        nonExisting(); // ! calling here puts no error on the console
        console.log('Promise.then entered, msg:',msg);
    })
    .then(function noop () {}, console.log.bind(console, 'An error was thrown'));

关于javascript - 异步 node.js 代码(使用 Q)不写入标准错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26928833/

相关文章:

javascript - Google Chrome 新标签页无法创建指向 chrome 的链接 ://apps

javascript - TypeError : res. sendFile 不是函数

javascript - 在 Node Js 中从字符串转换为 DateTime

node.js - Knex.js - Node 进程永远不会退出,如何优雅地关闭它 - 但只有当所有查询都得到解决时?

javascript - jQuery - 将垂直菜单更改为水平菜单

javascript - 如何控制 IE 中 onbeforeunload 的 Action ?

javascript - 我想将数据库中的数据与 googlelocation 下拉列表进行匹配

javascript - 如何将 angular-ui modal templateURL 与 Node/快速路由一起使用

Node.js Stream API 泄​​漏

c# - 如果我在不同的线程上同步运行,它会使每个线程异步吗?