如何使用函数扩展数组并在Promise.all()中调用它们

时间:2020-10-05 10:20:39

标签: javascript promise

假设我有一个包含可调用对象的数组:

const arr = [ obj1, obj2, obj3, ... ]

在我的情况下,这些对象还返回Promise,并且可以通过.doSomething()执行,例如:

arr[0].doSomething()

我需要将它们全部放到Promise.all()中,我想知道是否存在使用扩展运算符...的方法?

Promise.all(arr)无效,因为我必须在每个对象上调用doSomething()。像这样:

Promise.all((...arr) => a.doSomething())

1 个答案:

答案 0 :(得分:3)

扩展语法在这里无济于事。

您需要使用curses方法创建一个新数组,其中包含对.map()数组中的每个元素调用.doSomething()的结果。然后,应将此新数组传递给Promise.all

arr

或者您可以一行完成

const transformedArr = arr.map(o => o.doSomething());
Promise.all(transformedArr);