2016-05-16 60 views
2

我是nodejs的新手,試圖編寫第一個較大的項目。不幸的是,當我在Q fullfilment句柄中犯了一個錯誤時,我無法與nodejs退出並沒有錯誤。nodejs + Q承諾:在履行處理中沒有引用異常

實施例:

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 

與由於 「imnotexisting」 部分沒有語法/參考或者任何其他錯誤。 除了fullfilment句柄外,同樣的錯誤會拋出erorr,因爲它應該如此。

我在Ubuntu上使用nodejs 4.4.4。

+0

同樣適用於nodejs 6.1.0 –

+0

任何幫助或評論?這個問題使得我所有的拼寫錯誤都變得至關重要 - 因爲我的項目現在非常複雜 - 有許多異步路徑和長循環 - 應用程序內部的一些執行路徑失敗,沒有錯誤信息。跟蹤他們需要年齡... –

回答

0

OK,我發現這一點:

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未定義