我使用“promise”(但也尝试了“bluebird”)npm模块密集使用Promises包装异步代码。我并不感到惊讶它不处理异步抛出:
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存在非公开异常(我期望这种行为)。
此外,我尝试过基于“域”的错误处理:
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");
});
这种代码行为要好得多,但正如预期的那样 - 调用'reject'函数。
所以问题是:
答案 0 :(得分:0)
您可以使用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()
函数。