我有一些做同样事情的承诺,我希望以编程方式向他们添加 catch
语句,然后对它们运行Promise.all . 我有一些实现这个目标的想法,但它一直在我的脸上爆炸 .
let promises = [
Promise.reject('derp'), // Naïve test
new Promise((resolve, reject) => { // Assumed this ran out of main loop
reject('whayyy')
}),
new Promise((resolve, reject) => { // really assumed this ran out of main loop
process.nextTick(() => reject('nooooon'))
})
]
//fails
for(let promise of promises){
promise.catch((err) => { return 'fixed programatically'} )
}
Promise.all(promises).then((things) => {
console.log("Expect to make it here with no problems")
console.log(things)
})
我一直为这三个承诺得到这个:
(node:25148) UnhandledPromiseRejectionWarning: derp|whayy|nooooon
(node:25148) UnhandledPromiseRejectionWarning: Unhandled promise rejection.
This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
有谁知道如何正确地做到这一点?
2 回答
您将需要使用调用catch的结果的新Promise替换数组中的每个Promise . 否则你仍然只是在数组中有原始(被拒绝)的承诺,然后
Promise.all
最终再次拒绝,因为你没有 grab 它,你得到一个未处理的承诺拒绝错误 .替换数组中的promises的最好方法可能是在整个数组上使用Array#map:
完整代码(使用setTimeout以便它可以在浏览器中运行):
只要数组中的一个promise失败,Promise.all就会完全失败 .
要解决这个问题,请使用map函数 .
因此,我们在上面所做的是回归新的承诺并始终解决它 . 然后把它传递给Promise.all