简体   繁体   English

在 Promise.all() 中编写多个映射函数

[英]Writing multiple map functions in Promise.all()

I've two working blocks of Promise.all() in a single method.我在一个方法中有两个 Promise.all() 工作块。 I want to combine these two Promise.all() into one.我想将这两个 Promise.all() 合二为一。 The individual Promise.all() includes a map function that performs an asynchronous task.单个 Promise.all() 包括一个执行异步任务的映射函数。 Example:例子:

let obj1 = [], obj2 = [];
await Promise.all(container1.map(async (item)=>{
   obj1.push(await dbCall(item));
}))

await Promise.all(container2.map(async (item)=>{
   obj2.push(await dbCall(item));
}))

The above piece of block populates the dB as well as the local containers (obj1,obj2)上面的块填充了 dB 以及本地容器 (obj1,obj2)

Whereas, including these two map functions in single Promise.all([map1,map2]) does not populate the local containers (obj1,obj2) (dB gets updated as expected)然而,在单个 Promise.all([map1,map2]) 中包含这两个 map 函数不会填充本地容器 (obj1,obj2)(dB 按预期更新)

How can I include two map functions in single Promise.all()?如何在单个 Promise.all() 中包含两个映射函数?

you first try to merge the two arrays and then您首先尝试合并两个数组,然后

let obj = [];
container1.foreach((item)=>{
    obj.push(dbCall(item));
})
container2.foreach((item)=>{
    obj.push(dbCall(item));
})

await Promise.all(obj)

Keep in mind that Array.map returns a new array , in this case an array of Promises since async/await functions always return Promises.请记住, Array.map返回一个新数组,在这种情况下是一个 Promises 数组,因为 async/await 函数总是返回 Promises。 So your example of passing [map1, map2] will be a two-dimensional array;所以你传递[map1, map2]例子将是一个二维数组; it'll be an array of arrays of Promises.它将是一组 Promise 数组。 Something like this:像这样的东西:

[[Promise1, Promise2, Promise3, ...], [Promise4, Promise5, Promise6...]]

The Promise.all function expects an array of Promises, not an array of arrays of Promises, hence it fails. Promise.all 函数需要一个 Promises 数组,而不是一个 Promises 数组数组,因此它失败了。 You just need to pass it the correct structure of array, which you can do with Array.concat (for ES5 syntax) or the spread operator (for ES6 syntax).你只需要向它传递正确的数组结构,你可以使用Array.concat (对于 ES5 语法)或扩展运算符(对于 ES6 语法)。

Promise.all(map1.concat(map2));
// OR
Promise.all([...map1, ...map2]);

First simplify your code from that array push ing to首先简化您的代码从该数组push

const obj1 = await Promise.all(container1.map(dbCall));
const obj2 = await Promise.all(container2.map(dbCall));

Then, to run both of them concurrently, add another Promise.all around them:然后,要同时运行它们,在它们周围添加另一个Promise.all

const [obj1, obj2] = await Promise.all([
  Promise.all(container1.map(dbCall)),
  Promise.all(container2.map(dbCall)),
]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM