你可以做一些更短的
Array.from(map1.entries())
可以重写为[...map1]
- 在我看来,
doSomeOtherThing
不依赖于doSomeThing
,所以我们可以同时称它们为两个
await Promise.all(
[...map1].flatMap(([key, val]) => [
doSomeThing(key, val),
doSomeOtherThing(key, val),
])
)
const doSomeThing = (key, val) =>
new Promise(res => {
console.log("doSomeThing start", key, val)
setTimeout(() => {
console.log("doSomeThing finish", key, val)
res()
}, 1000)
})
const doSomeOtherThing = (key, val) =>
new Promise(res => {
console.log("doSomeOtherThing start", key, val)
setTimeout(() => {
console.log("doSomeOtherThing finish", key, val)
res()
}, 2000)
})
async function test() {
const map1 = new Map()
map1.set("a", 1)
map1.set("b", 2)
map1.set("c", 3)
/*
await Promise.all(
Array.from(map1.entries()).map(async ([key, value]) => {
await doSomeThing(key, value)
await doSomeOtherThing(key, value)
})
)
*/
await Promise.all(
[...map1].flatMap(([key, val]) => [
doSomeThing(key, val),
doSomeOtherThing(key, val),
])
)
}
test().then(() => {
console.log("done")
})