2014-11-14 30 views
1

我在編寫異步node.js代碼時遇到以下問題:在異步塊內拋出的錯誤不會向控制檯輸出任何內容標準錯誤只是默默地失敗。異步node.js代碼(使用Q)不寫入標準錯誤

這裏是一個自包含的工作示例重現該問題,在這裏我所說的不存在的功能之外,一個異步回調中:由//表示

注意線!評論

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 

我運行代碼從標準的Windows命令提示符下,用node file.js命令。 (我在Windows 7上運行節點0.10.32)

爲什麼會發生這種情況,我該如何解決這個問題?

回答

2

這是一個預期的行爲。

Q API Reference:

由於然後回調拋出的異常被消耗並轉化成 排斥,在所述鏈的端部的例外是容易 一不小心,默默地忽略。

如果你想如果鏈中的任何承諾被拒絕或異常的解析處理器拋向傳播異常,使用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'));