使用bluebird承诺进行异步异常处理处理此方案的最佳方法是什么。我处于受控环境中,我不想崩溃。var Promise = require('bluebird');function getPromise(){
return new Promise(function(done, reject){
setTimeout(function(){
throw new Error("AJAJAJA");
}, 500);
});}var p = getPromise();
p.then(function(){
console.log("Yay");
}).error(function(e){
console.log("Rejected",e);
}).catch(Error, function(e){
console.log("Error",e);
}).catch(function(e){
console.log("Unknown", e);
});从setTimeout中抛出时,我们总是得到:$ node bluebird.js
c:\blp\rplus\bbcode\scratchboard\bluebird.js:6
throw new Error("AJAJAJA");
^Error: AJAJAJA
at null._onTimeout (c:\blp\rplus\bbcode\scratchboard\bluebird.js:6:23)
at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)如果抛出发生在setTimeout之前,那么bluebirds catch会把它拿起来:var Promise = require('bluebird');function getPromise(){
return new Promise(function(done, reject){
throw new Error("Oh no!");
setTimeout(function(){
console.log("hihihihi")
}, 500);
});}var p = getPromise();
p.then(function(){
console.log("Yay");
}).error(function(e){
console.log("Rejected",e);
}).catch(Error, function(e){
console.log("Error",e);
}).catch(function(e){
console.log("Unknown", e);
});结果是:$ node bluebird.jsError [Error: Oh no!]哪个好 - 但是如何在节点或浏览器中处理这种性质的流氓异步回调。
2 回答
开满天机
TA贡献1786条经验 获得超13个赞
现在我知道promise在异步回调中没有捕获错误。这是我测试的3个例子。
注意:拒绝呼叫后,功能将继续运行。
示例1:拒绝,然后在promise构造函数回调中抛出错误
示例2:拒绝,然后在setTimeout异步回调中抛出错误
示例3:拒绝,然后返回setTimeout异步回调以避免崩溃
// Caught// only error 1 is sent// error 2 is reached but not send reject againnew Promise((resolve, reject) => { reject("error 1"); // Send reject console.log("Continue"); // Print throw new Error("error 2"); // Nothing happen}) .then(() => {}) .catch(err => { console.log("Error", err); });// Uncaught// error due to throw new Error() in setTimeout async callback// solution: return after rejectnew Promise((resolve, reject) => { setTimeout(() => { reject("error 1"); // Send reject console.log("Continue"); // Print throw new Error("error 2"); // Did run and cause Uncaught error }, 0);}) .then(data => {}) .catch(err => { console.log("Error", err); });// Caught// Only error 1 is sent// error 2 cannot be reached but can cause potential uncaught error if err = nullnew Promise((resolve, reject) => { setTimeout(() => { const err = "error 1"; if (err) { reject(err); // Send reject console.log("Continue"); // Did print return; } throw new Error("error 2"); // Potential Uncaught error if err = null }, 0);}) .then(data => {}) .catch(err => { console.log("Error", err); });
添加回答
举报
0/150
提交
取消