Categories
JavaScript Answers

How to make multiple Axios requests at the same time with JavaScript?

Spread the love

Sometimes, we want to make multiple Axios requests at the same time with JavaScript.

In this article, we’ll look at how to make multiple Axios requests at the same time with JavaScript.

How to make multiple Axios requests at the same time with JavaScript?

To make multiple Axios requests at the same time with JavaScript, we can use the Promise.all method.

For instance, we write:

(async () => {
  const [{
    data: data1
  }, {
    data: data2
  }] = await Promise.all([
    axios.post('https://jsonplaceholder.typicode.com/posts'),
    axios.post('https://jsonplaceholder.typicode.com/posts'),
  ])
  console.log(data1, data2)
})()

We call axios.post to make POSTS requests and we put them both in an array.

Then we call Promise.all with the array to make the requests simultaneously.

Finally, we use the await keyword to run the promises and get the response from the data property.

Conclusion

To make multiple Axios requests at the same time with JavaScript, we can use the Promise.all method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *