nodejs + Q承诺:执行句柄中没有引用exception

我是nodejs的新手,试图编写第一个更大的项目。 不幸的是,当我在Q fullfilment句柄里面犯了一个错误时,我被nodejs退出了,没有错误。

例:

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。

好的,我find了这个:

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