用蓝鸟承诺进行asynchronousexception处理

什么是处理这种情况的最佳方法。 我在一个受控制的环境中,我不想崩溃。

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) 

如果throw在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.js Error [Error: Oh no!] 

哪一个很好 – 但是如何在节点或者浏览器中处理这种性质的stream氓asynchronouscallback。

Promise不是域 ,它们不会从asynchronouscallback中捕获exception。 你不能这样做。

但是承诺会捕获从then / catch / Promise构造函数callback中抛出的exception。 所以使用

 function getPromise(){ return new Promise(function(done, reject){ setTimeout(done, 500); }).then(function() { console.log("hihihihi"); throw new Error("Oh no!"); }); } 

(或只是Promise.delay )来获得所需的行为。 永远不要抛出定制(非承诺)的asynchronouscallback,总是拒绝周围的承诺。 如果真的需要使用try-catch

感谢@Bergi。 现在我知道承诺不会在asynchronouscallback中捕获错误。 这是我testing过的3个例子。

注意:呼叫拒绝后,function将继续运行。

例1:拒绝,然后在承诺构造函数callback中抛出错误

例2:拒绝,然后在setTimeoutasynchronouscallback中抛出错误

例3:拒绝,然后返回setTimeoutasynchronouscallback,以避免崩溃

 // Caught // only error 1 is sent // error 2 is reached but not send reject again new 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 reject new 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 = null new 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); });