promise.all_Promise.all用于拒绝和解决

promise.all

Promises have been an incredible addition to JavaScript; they save us callback hell, make coding async more maintainable, and and allow us to keep track of multiple async processes at a time.  Promise.all comes to mind, allowing us to react when multiple promises have been resolved.  Unfortunately Promise.all only resolves when all promises are resolved, so if any of the promises fail, the catch is called instead of then:

承诺已经成为JavaScript的不可思议的补充。 它们为我们省去了回调的麻烦,使异步编码更易于维护,并允许我们一次跟踪多个异步进程。 Promise.all在脑海,让我们在解决多个承诺时作出React。 不幸的是Promise.all仅在所有promise都解决时才解决,因此,如果任何promise失败,则调用catch而不是then:


Promise.all([
    Promise.resolve(1),
    Promise.reject(0)
])
.then(() => { console.log('resolved!'); })
.catch(() => { console.log('failed!') });
// >> failed!


This is a problem if you want the same functionality to be executed regardless of if any promise in the array is rejected.  You could provide the same function to then and catch but that could lead to maintenance issues and occasional "WTF IS THIS?!" comments from other engineers.

如果您希望执行相同的功能而不管阵列中的任何承诺是否被拒绝,这都是一个问题。 您可以提供相同的功能then catch但是可能导致维护问题,并偶尔出现“ WTF就是这个?!”。 其他工程师的意见。

So what should we do when we want Promise.all to trigger functionality regardless of any rejections?  Jake Archibald has the answer:

那么,当我们希望Promise.all触发功能而无论Promise.all拒绝时,该怎么办? 杰克·阿奇博尔德有答案


Promise.all(promises.map(p => p.catch(() => undefined)));


Each promise's catch callback returns undefined which allows the promise's failure to be handled as success. To prove it works, consider this snippet:

每个promise的catch回调返回undefined ,这允许将promise的失败视为成功。 为了证明它可行,请考虑以下代码段:


Promise.all([
    // Resolves
    Promise.resolve(1), 
    // Rejects after 2 seconds
    new Promise((resolve, reject) => setTimeout(() => reject(1), 2000))
].map(p => p.catch(() => undefined))).then(() => console.log('done!'));

// >> done!


Despite the second promise being rejected, the Promise.all then is called! In the future we'll be able to use Promise.prototype.finally to more easily handle success and failure.

尽管被拒绝的第二个承诺,请Promise.all then叫! 将来,我们将能够最终使用Promise.prototype.finally来更轻松地处理成功和失败。

Thank you to Jake for this awesome trick!

谢谢杰克这个很棒的把戏!

翻译自: https://davidwalsh.name/promises-results

promise.all

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值