为了账号安全,请及时绑定邮箱和手机立即绑定

防止 Promise.all 在第一个错误时拒绝的规范方法是什么?

防止 Promise.all 在第一个错误时拒绝的规范方法是什么?

温温酱 2021-06-01 17:48:05
我有以下代码await doAllCats();await doAllDogs();console.log("Finished processing Cats and Dogs ")function doAllCats() {  let promiseArray = [];  for(let cat of cats) {    promiseArray.push(doOneCat(cat));  }  return Promise.all(promiseArray);}function doOneCat(cat) {  let promise = doSomeAsyncStuffWithACat(cat);  promise.catch((err)=> {    console.error("there was a problem with "+cat+" but processing should continue as normal for the other cats and dogs");  })  return promise; }当所有的猫和狗都成功时,这工作正常。但是,有时猫会失败,当发生这种情况时,我会在最高级别收到异常。处理 cat 失败的代码在里面doOneCat并且正确执行。然而,失败的承诺仍然存在promiseArray,所以我过早地“完成”了。防止Promise.all拒绝第一个异常的最简单/规范的方法是什么?
查看完整描述

2 回答

?
烙印99

TA贡献1829条经验 获得超13个赞

只需返回捕获的 Promise,这样拒绝就不会冒泡到Promise.all(然后它不会退出):


 return promise.catch((err) => {

   console.error("there was a problem with "+cat+" but processing should continue as normal for the other cats and dogs");

    return /*some flag that indicates that this one did throw */;

 });

将来,将有Promise.allSettled来解决那个确切的情况。


查看完整回答
反对 回复 2021-06-03
  • 2 回答
  • 0 关注
  • 165 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信