简体   繁体   中英

Fire async calls in order

I've got some code right now that looks like this:

const a = await function1();
const b = await function2();
const c = await function3();

However I'm trying to optimise for speed and don't want the delays. I have tried doing the following

[const a, const b, const c] = await Promise.all([function1, function2, function3)]

This works fine however the problem I then have is that I can't preserve the order of the calls initiated from my machine. As I send out a nonce on each request the end server will decline the request if it goes in order 1 -> 3 -> 2 instead of 1->2->3.

Is there a way to use the Promise.all which doesn't wait for each function to complete but still retain the order of the calls?

If you do:

const [a, b, c] = await Promise.all([function1(), function2(), function3()];

the synchronous part of function1 will run first, followed by the synchronous part of function2 , followed by the synchronous part of function3 . At that point, they're in a race for completion. Regardless of the order they complete in, you'll get the results in order ( a is the result of function1 , b of function2 , etc.).

If the server requires that the asynchronous part of function1 finish before function2 starts, then you have to use your original code. The only control you have in the client-side code is when the processes start .

However , that doesn't mean it's not possible to optimize them a bit, but it depends a lot on what they do. For instance, if the important thing is that you receive the headers sent in response to function1 's request before you start function2 , but function1 does further processing after receiving the headers (such as reading and doing something with the body of the response), you can optimize that but splitting function1 into two parts: The part that starts the process and consumes the headers, and the part that consumes the body and does something with it.

If you did that, you'd do it like this:

// Do the first part in series
const r1 = await function1PartA();
const r2 = await function2PartA();
const r3 = await function3PartA();
// Do the remainder in parallel
const [a, b, c] = await Promise.all([
    function1PartB(r1),
    function2PartB(r2),
    function3PartB(r3)
]);

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