Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do parallel requests and return an object containing all parallel responses in Javascript?

Tags:

javascript

So I know that I can make parallel requests and wait for it in Javascript / ReactNative using Promise.all() or Promise.allSettled():

await Promise.all([
    request1(),
    request2(),
    request3(),
]);

But how if I want to do something like this:

var result = {}
await Promise.all([
    result["response1"] = request1(),
    result["response2"] = request2(),
    result["response3"] = request3()
]);
return result;

Currently I do workaround like this:

request1 = async() => {
    return client.post(....).then(async(response) => {
        this.request1response = response
        return response
    })
}
// same thing with request2() and request3()

parallelRequest = async() => {
    var result = {}
    await Promise.all([
        request1(),
        request2(),
        request3()
    ]);
    result["response1"] = this.request1response
    result["response2"] = this.request2response
    result["response3"] = this.request3response
    delete this.request1response
    delete this.request2response
    delete this.request3response
    return result;
}

But I think this is a bad pattern, prone to bug (if the parallelRequest is called multiple times in quick succession) and I want to seek a better way to implement this.

like image 668
Chen Li Yong Avatar asked Mar 07 '26 04:03

Chen Li Yong


1 Answers

You should do something like this:

const parallelRequest = async () => {
  const [response1, response2, response3] = await Promise.all([
    request1(),
    request2(),
    request3(),
  ]);
  const result = { response1, response2, response3 };
  return result;
};

Because Promise.all return an array of all the responses, in the same order as the array of Promises provided.

  • step 1: destructure the response array into all the responses
  • step 2: build the response object using variables' name as keys in the result object
  • step 3: return your result object

you could also directly return { response1, response2, response3 }

like image 178
Apolo Avatar answered Mar 09 '26 17:03

Apolo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!