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!
谢谢杰克这个很棒的把戏!
promise.all