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.
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.
you could also directly return { response1, response2, response3 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With