22

I need to process an unknown number of AJAX requests (1 or more) with axios, and I am not sure how to handle the response. I want something along the lines of:

let urlArray = [] // unknown # of urls (1 or more)

axios.all(urlArray)
.then(axios.spread(function () {
  let temp = [];
  for (let i = 0; i < arguments[i].length; i++)
    temp.push(arguments[i].data);
}));

where arguments will contain the callback responses sent by axios. The problem is that arguments contains the given string urls instead of the actual responses. How can I resolve this problem?

treeblah
  • 1,205
  • 2
  • 11
  • 26

1 Answers1

45

You somewhere will need to make the actual requests. And then don't use spread but only then to receive the array of results:

let urlArray = [] // unknown # of urls (1 or more)

let promiseArray = urlArray.map(url => axios.get(url)); // or whatever
axios.all(promiseArray)
.then(function(results) {
  let temp = results.map(r => r.data);
  …
});
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • I'm pretty sure you need the spread ... My results are just Array(3) [ undefined, undefined, undefined ] – Micheal J. Roberts Aug 27 '20 at 08:45
  • @MichealJ.Roberts If you are getting an array, and want to work with an array instead of three specific values, then you should not use `spread` (and even if you do, just use modern destructuring syntax instead of `spread`). If your problem is that you get `undefined` instead of some expected value, that has nothing to do with `spread` but with the function that is creating your promises. – Bergi Aug 27 '20 at 10:30