asynchronousnode.js代码(使用Q)不写入标准错误

在编写asynchronousnode.js代码时,我遇到了以下问题: 在asynchronous块内抛出的错误不会将任何内容打印到控制台标准错误 ,它们只是失败而已。

下面是一个自包含的工作示例来重新创build问题,我在asynchronouscallback的外部和外部调用一个不存在的函数:

注意//表示的行! 注释

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上运行节点0.10.32)

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

这是一个预期的行为。

从Q API参考:

由于在callback中抛出的exception被消耗并转化为拒绝,链末端的exception很容易被意外地忽略。

如果您希望在链中的任何承诺被拒绝或解决scheme处理程序中引发exception的情况下传播exception,请使用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'));