在Map()的条目上使用Promise.all [英] Using Promise.all on the entries of a Map()
本文介绍了在Map()的条目上使用Promise.all的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在为某些键/值对使用Map
I am using a Map for some key/value pairs
let myMap = new Map()
myMap.set('foo', 'bar')
myMap.set('foo2', 'bar42')
对于每个Map条目,我执行一个返回Promise的函数.所有这些承诺都可以使用Promise.all
并行执行.
For every Map entry I execute a function which returns a Promise. All these Promises can be executed in parallel using Promise.all
.
这是我现在的操作方式:
This is how I do it right now:
let mapPromises = []
myMap.forEach((value, key) => {
mapPromises.push(MyModel.forge({key, language, value}).save())
})
await Promise.all(mapPromises)
除了将所有函数调用放入数组然后触发Promise.all
?
推荐答案
我能想到的最简单的代码是
The simplest code I could come up with is
await Promise.all(Array.from(myMap, ([key, value]) =>
MyModel.forge({key, language, value}).save())
);
请参见 Array#from 文档
这篇关于在Map()的条目上使用Promise.all的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文