Prateek Anand
Prateek Anand

Reputation: 39

How to send n concurrent request with axios

I have an array let's say it fruits, which contains n values. Now, I want to generate a new URL using the values in the arrays, and send concurrent requests through axios concurrency feature. Since, they have updated this feature, and deprecated the old way of doing thing.

I googled about it but my problem isn't solved. Blogs are suggesting to create a new function for every request I will make to server, through axios. But in my case, the number of requests depend on the values of array (up to a certain limit). Sometimes I want to send only one request and sometimes three.

Upvotes: 0

Views: 1285

Answers (1)

Bergur
Bergur

Reputation: 4057

I would do what sp00m suggests in his comment:

Map the array to promise and use Promise.all to resolve them

const fruits = ['Banana', 'Orange', 'Apple']

const promiseArray = fruits.map(fruit => {
  return axios.get('/fruits/' + fruit).then(res => res.json())
})

Promise.all(promiseArry)
  .then(allresults => {
    console.log('got everything')
    console.log(allresults)
  })
  .catch(err => {
    console.log('one of the promise failed')
  })

..or if you want to send them sequentially, one by one.

Map the array to promise functions and then reduce it.

const fruits = ['Banana', 'Orange', 'Apple']

const promiseFunctions = fruits.map(fruit => {
  return () => axios.get('/fruits/' + fruit).then(res => res.json())
})

promiseFunctions.reduce((p, fn) => p.then(fn), Promise.resolve())

Upvotes: 3

Related Questions