How to write multiple promises simultaneously

Manusha Dananjaya
2 min readJun 5, 2024

--

Let's try to get random 3 API calls for dogs' images, not just one. So we simply await 3 API calls one after the other. like this,

3 API calls

But why do we wait second API call and wait for the first one and the third API call waits for the second one?

That would add unnecessary waiting time when we could just run all the promises at the same time.

Now let me show you the solution for this how we call these 3 promises at the same time.

the solution is we do not want to await the promise instead we can save the promise into a variable.

so again we want to now save the promise and not the resolved value of the promise.

it's just basically like this,

Now you can see that res1Pro means result1 promise, which is the variable that contains res1 promise.

now what we do await is “promise.all” okay.

now into “promise.all” we passed an array of promises [res1Pro, res2Pro, res3Pro].

then again we have these three promises in these three variables and we can pass an array containing these three promises into a “promise.all”.

If we then await that, it will run these three promises all at the same time. And then save the three results [res1,res2,res3] array.

--

--

Manusha Dananjaya
Manusha Dananjaya

Written by Manusha Dananjaya

Undergraduate Student University of Moratuwa Sri Lanka.

No responses yet