Node.js承诺和asynchronousexception

我主要使用Promises来封装asynchronous代码,使用“promise”(但也试过“bluebird”)npm模块。 我不惊讶,它不处理asynchronous抛出:

var Promise = require("promise"); // also tried require("bluebird") here function asyncThrow() { return new Promise(function(resolve, reject) { process.nextTick(function() { throw new Error("Not handled!"); }) }); } asyncThrow() .then(function() { console.log("resolved"); }) .catch(function() { console.log("rejected"); }); 

在这个代码执行过程中,node.js存在unhandedexception(我期望这种行为)。

另外我已经尝试过基于“域”的error handling:

 var Promise = require("promise"); // also tried require("bluebird") here var domain = require("domain"); function asyncThrow() { return new Promise(function(resolve, reject) { var d = domain.create(); d.on("error", reject); d.run(function() { process.nextTick(function() { throw new Error("Not handled!"); }) }); }); } asyncThrow() .then(function() { console.log("resolved"); }, function() { console.log("rejected"); }) .catch(function() { console.log("catch-rejected"); }); 

这个代码的行为好得多,但是正如预期的那样 – 调用了“拒绝”函数。

所以问题是:

  1. 处理asynchronous代码时如何强制“catch-reject”函数调用?
  2. 这种方法是否会造成显着的性能损失
  3. 也许你可以build议更好的方法来处理这种例外?

你可以使用Promise.denodeify(fn)来实现这一点。

 var Promise = require("promise"); function asyncThrow() { return new Promise(function(resolve, reject) { // Denodify the process.nextTick function var nextTick = Promise.denodeify(process.nextTick) // Utilize nextTick and return the promise return nextTick.then(function() { throw new Error("Not handled!"); }) }); } asyncThrow() .then(function() { console.log("resolved"); }) .catch(function() { console.log("rejected"); }); 

这将导致调用.catch()函数。