[英]How can I call multiple asynchronous depended functions asynchronously for each iteration?
我有一些功能,
const firstResult = await firstFunction(parameters)
const secondResult = await secondFunction(firstResult)
const finalResult = await finalFunction(secondResult)
它们是异步函数,返回一些承诺。 现在有一个场景,比如我有一个参数数组,这些参数在每次迭代时传递给 `firstFunction,它应该遵循相同的执行流程。 像这样的东西:
const results = arrayOfParamters.map(async parameter => {
const firstResult = await firstFunction(parameters)
const secondResult = await secondFunction(firstResult)
const finalResult = await finalFunction(secondResult)
return finalResult
})
那么我怎样才能更有效地实现这一目标呢? 其中一个有效的解决方案,我可以想像的是执行firstFunction
第一个parameter
,开始执行secondFunction
和直到然后承诺secondFunction
满足,开始执行firstFunction
为下一次迭代arrayOfParameters
。 有什么办法可以实现这一目标吗? 如果整个循环要同步执行,那么Promise.all
似乎不值得。
您的代码已经设置为执行此操作。
它将从运行数组元素 0 的映射代码开始。 它同步调用firstFunction
但随后它遇到了await
,因此映射函数返回一个承诺。 这个承诺被放在results
元素 0 中。 然后它对元素 1 执行相同的操作,然后是 2,等等。所以它会为数组的每个元素调用firstFunction
,并将一个 promise 数组分配给results
,但它们都不会阻塞或等待。
现在已经创建了 promise 数组,因此代码继续执行此行之后的任何内容。 随着时间的推移,对firstFunction
的调用将开始完成, async
函数将继续,为数组的每个元素调用secondFunction
(不一定以完全相同的顺序,因为这是在不可预测的时间发生的)。 然后最终他们都会做第三个功能,最后他们会解决他们对finalResult
的承诺。
所以你的代码中唯一缺少的是知道什么时候完成,为此你需要Promise.all
:
const promises = arrayOfParamters.map(async parameter => {
const firstResult = await firstFunction(parameter)
const secondResult = await secondFunction(firstResult)
const finalResult = await finalFunction(secondResult)
return finalResult
})
const results = await Promise.all(promises)
因为Promise.then
将结果作为参数链接到下一个函数,您可以使用它代替async
await
你可以像这样使用Promise.all
:
const promiseChain = arrayOfParamters.map((parameter) => firstFunction(parameter).then(secondFunction).then(finalFunction));
const results = await Promise.all(promiseChain);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.