简体   繁体   English

处理最大独立和依赖异步/等待作业的正确方法(承诺)

[英]Correct way to handle max of independent and dependent async/await jobs (Promises)

I have four asynchronous processes that fetch from different sources, namely process A, B, C and D.我有四个从不同来源获取的异步进程,即进程 A、B、C 和 D。

Process A, B and C are independent of each other, but D depends on data from C.进程 A、B 和 C 相互独立,但 D 依赖于来自 C 的数据。

As far as possible, I want A and B to be fetched independently on C and D, but I want to keep the result of A, B, C and D for the procedure that follows.尽可能地,我希望 A 和 B 在 C 和 D 上独立获取,但我想保留 A、B、C 和 D 的结果以用于后面的过程。

So I'm trying to come up with the correct way to express this functionality.所以我试图想出正确的方式来表达这个功能。

Something like就像是

const results = await Promise.allSettled([A, B, C]);
const resultD = await D(results[2].value);

means that I'm waiting to perform D until A, B, C are all finished, but in this case A or B might take significantly more time than C.意味着我正在等待执行 D,直到 A、B、C 全部完成,但在这种情况下,A 或 B 可能比 C 花费更多的时间。

Likewise,同样地,

const results = await Promise.allSettled([A, B, C, D(await C)]);

Doesn't seem quite right?好像不太对劲? I don't want C performed twice, and I also want to keep the result.我不希望 C 执行两次,我也想保留结果。

What would be the correct way to go about solving this elegantly?优雅地解决这个问题的正确方法是什么?

You can group C and D together and resolve it with A and B .您可以将CD组合在一起并使用AB解决它。

Let's understand the snippet below:让我们理解下面的片段:

Consider the functions A , B , C & D equivalent to fetching from four different APIs.考虑函数ABCD等价于从四个不同的 API 获取。 Also, notice how D needs some data, that it would get from C .另外,请注意D如何需要一些数据,这些数据将从C获得。

And in the main function we're resolving A , B independently and we're resolving D only after C has finished.main函数中,我们独立解析AB ,并且只有在C完成后才解析D

 const sleep = (delay, data) => new Promise(res => setTimeout(() => res(data), delay)); const A = () => sleep(100).then(() => "A") const B = () => sleep(200).then(() => "B") const C = () => sleep(100).then(() => "C") const D = (inp) => sleep(100).then(() => inp + "D") function main() { const promises = [A(), B(), C().then(res => D(res))]; Promise.all(promises).then(console.log); } main();

You can also use Promise.allSettled but make sure you understand the difference between allSettled and all .您也可以使用Promise.allSettled但请确保您了解allSettledall之间的区别。

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

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