【发布时间】:2017-08-06 02:39:11
【问题描述】:
背景
我正在使用 Promise,并且我有许多函数可能会或可能不会返回 Promise,并且可能会或可能不会失败,如下例所示:
//does not return a Promise, simply a string
let goodFun = function(){
return "I like bananas!";
};
//blows up!
let badFun = function(){
throw "A general error blaahh!";
};
//You get the point ...
由于这些函数可能会或可能不会返回 Promises,并且可能会或可能不会失败,因此我需要等待它们全部执行。为了实现这一点,我有一个函数可以调用它们并等待它们执行:
let asyncFun = function(){
return Promise.all([badFun(), goodFun()]);
};
问题
到目前为止一切顺利。我的代码调用asyncFun,我希望它的某些功能实际上会失败。为了做好准备,我添加了一个问题:
let executor = function(){
let numbsArray = [1, 2, 3];
let respArray = [];
for(let num of numbsArray){
respArray.push(
asyncFun()
.catch( error => console.log(`I failed with ${error} and ${num}`))
);
}
return Promise.all(respArray);
};
问题是catch 根本没有捕捉到任何东西!
即使在调用executor 的函数中添加一个catch 也没有捕捉到任何东西!
executor()
.catch(error => console.log("Failed miserably to catch error!"));
研究
我真的不明白为什么我的 catch 子句没有捕捉到异常。为了找出答案,我阅读了这个讨论:
这让我相信我的所有函数 goodFun 和 badFun 无论如何都必须返回一个承诺。
这让我很困惑,因为根据MDN documentation,数组可能包含一个 Promise,或者一个结果(如字符串或数字)。
我还想避免在我的函数中添加 更多 样板代码 ....
问题:
- 如何修复我的代码,以便添加最低限度或样板代码的捕获器起作用?
代码
let goodFun = function() {
return "I like bananas!";
};
let badFun = function() {
throw "A general error blaahh!";
};
let asyncFun = function() {
return Promise.all([badFun(), goodFun()]);
};
let executor = function() {
let numbsArray = [1, 2, 3];
let respArray = [];
for (let num of numbsArray) {
respArray.push(
asyncFun()
.catch(error => console.log(`I failed with ${error} and ${num}`))
);
}
return Promise.all(respArray);
};
executor()
.catch(error => console.log("Failed miserably to catch error!"));
【问题讨论】:
标签: javascript node.js promise es6-promise