简体   繁体   中英

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.

Process A, B and C are independent of each other, but D depends on data from 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.

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.

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.

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 .

Let's understand the snippet below:

Consider the functions A , B , C & D equivalent to fetching from four different APIs. Also, notice how D needs some data, that it would get from C .

And in the main function we're resolving A , B independently and we're resolving D only after C has finished.

 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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