How to make parallel API requests in Nodejs

Ankit Kumar Rajpoot
2 min readMar 20, 2023

In this article we will learn how we can hit parallel API requests inside the javascript or nodejs, This question is important for the interview because the answer is simple but it’s related to promise.

There are two options-

  1. We can use the loop and hit the API one by one but it obviously it will take multiply n time, time means taken by one request.
  2. Second approach is the answer of this question, In this approach we can hit parallel request via promise.all functionality, via promise.all all api will hit togather and there is no sequence for perticular request.

Example

const ids = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // Array of ids
const axios = require('axios');

let func = async function(){
const responses = await Promise.all(
ids.map(async id => {
const res = await axios({
method: 'get',
url: `https://webhook.site/30b549b1-5d38-4dfa-b314-11276bc8cebc/${id}`,
responseType: 'stream'
}
); // Send request for each id
})
);
console.log(responses)
}

func();

That’s it for this time! I hope you enjoyed this post. As always, I welcome questions, notes, comments and requests for posts on topics you’d like to read. See you next time! Happy Coding !!!!!

--

--

Ankit Kumar Rajpoot

I’m a MERN Developer. ( Redux | AWS | Python ) I enjoy taking on new things, building skills, and sharing what I’ve learned.