Search code examples
javascriptasynchronouspromisees6-promise

JS, multi awaits with single promise


Will this code send more request

 const pr1 = request1();
 const pr2 = request2();
 const pr3 = request3();

 await Promise.all([pr1, pr2, pr3])

 const res1 = await pr1
 const res2 = await pr2
 const res3 = await pr3

than

 const pr1 = request1();
 const pr2 = request2();
 const pr3 = request3();

 const [res1, res2, res3] = await Promise.all([pr1, pr2, pr3])

What is the most efficient way to send multiple async requests using nodejs?


Solution

  • Will this code send more request

    No.

    It sends three requests.

    Then it waits for all of them to resolve.

    Then it waits for each of them to resolve (which takes no time because they have resolved already) assigning them to variables as it goes.

    Waiting for something to resolve does not start it from scratch.

    What is most efficient way to send multiple async requests using nodejs?

    I would be astonished if there were any practical performance differences between the two versions of the code.

    The second version, which uses destructuring, is (subjectively) easier to read.

    Write for the people maintaining your code (which is will often be you in 6 months time). Giving them code that is easy to maintain is going to save you more than trying to deal with microoptimisations.