我在编写异步 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)
为什么会发生这种情况,我该如何解决这个问题?
最佳答案
这是预期的行为。
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/