concurrent axios requests in javascript

To make concurrent axios requests in Javascript, we can use the Promise.all() method along with axios.all() or axios.spread() methods.

Here's an example code snippet using Promise.all() and axios.all():

index.tsx
const axios = require('axios');

const urls = ['https://jsonplaceholder.typicode.com/posts/1', 'https://jsonplaceholder.typicode.com/posts/2', 'https://jsonplaceholder.typicode.com/posts/3'];

const promises = urls.map(url => axios.get(url));

Promise.all(promises)
  .then(results => {
    console.log(results[0].data);
    console.log(results[1].data);
    console.log(results[2].data);
  })
  .catch(error => console.error(error));
435 chars
14 lines

This code uses Promise.all() to wait for all promises (axios requests) to resolve, and then it logs the results data.

Alternatively, we can use axios.spread() to handle the results data separately:

index.tsx
const axios = require('axios');

const urls = ['https://jsonplaceholder.typicode.com/posts/1', 'https://jsonplaceholder.typicode.com/posts/2', 'https://jsonplaceholder.typicode.com/posts/3'];

axios.all(urls.map(url => axios.get(url)))
  .then(axios.spread((res1, res2, res3) => {
    console.log(res1.data);
    console.log(res2.data);
    console.log(res3.data);
  }))
  .catch(error => console.error(error));
412 chars
12 lines

Here, axios.all() takes an array of promises (axios requests), and axios.spread() handles the results data separately.

gistlibby LogSnag