稍后以编程方式将捕获添加到多个promise

时间:2018-12-09 18:48:00

标签: javascript node.js promise

我有一些承诺可以做同样的事情,我希望以编程方式向他们添加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 个答案:

答案 0 :(得分:2)

您需要用调用catch的结果,用新的Promise替换数组中的每个Promise。否则,您仍然只是数组中的原始(被拒绝)promise,然后Promise.all最终再次被拒绝,由于您对此一无所获,因此会出现未处理的promise拒绝错误。

替换数组中的Promise的最佳方法可能是在整个数组上使用Array#map

promises = promises.map( promise => 
  promise.catch((err) => { return 'fixed programatically'} )
);

完整代码(使用setTimeout使其可以在浏览器中运行):

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
    setTimeout(() => reject('nooooon'),0)
  }),
  Promise.resolve( 'success case, doesn\'t need fixing' ),
]

promises = promises.map( promise => 
  promise.catch((err) => { return 'fixed programatically'} )
);

Promise.all(promises).then((things) => {
  console.log("Expect to make it here with no problems")
  console.log(things) 
})

答案 1 :(得分:-2)

Promise.all一旦数组中的承诺之一失败,将全部失败。

要解决此问题,请使用地图功能。

promises.map(promise => {
      return new Promise((resolve, reject) => {
        promise.then(resolve).catch(resolve);
      });
  });

因此,我们在上文中所做的工作是返回新的承诺并始终予以兑现。然后将其传递给Promise.all