0

How do I return value of stuff outside the for loop. I need to make an API call i amount of times and store the result each time. There is probably a duplicate question somewhere with the answer but I am unable to find it.

function getResponse() {
    var stuff = []
    
    for (let i = 0; i < length; i++) {
        axios.get(url + i)
            .then(res => res.forEach(item => {
                stuff.push(item)
            }))
    }
    // How do I return stuff from this function ?
}

console.log(getResponse())

I've tried making this function only do a call and then looping in another function which calls this but I get:

cannot read property then of undefined.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Vincent Nguyen
  • 1,555
  • 4
  • 18
  • 33

1 Answers1

1

How do I return stuff from this function ?

You can't. Its like "I want to get the newspaper of tomorrow". That won't work either. You have to wait until the next day to read the newspaper, or in your case, until all the data arrived at the browser. You cannot return the data directly, but a Promise that will deliver the data somewhen. In your case you can use Promise.all to unify an array of promises into a promise that resolves to an array:

function getResponse() {
  const promises = [];

  for (let i = 0; i < length; i++) {
    promises.push(axios.get(url + i));
  }

  return Promise.all(promises)
    .then(results => [].concat(...results));
}

So now if you do:

console.log(getResponse())

You get a promise. To get the actual data, you have to wait until the data arrives:

getResponse().then(console.log);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • Ok let me try to understand this – Vincent Nguyen Jun 01 '18 at 15:29
  • Ok I am making some progress, thanks. I will comment back if I run into any more issue and give you a green check – Vincent Nguyen Jun 01 '18 at 15:37
  • 1
    @vincent take your time, this is one of the most complicated things in javascript. I'm glad to help :) – Jonas Wilms Jun 01 '18 at 15:38
  • I am used to Vue/React where I can just make the call and set a variable to display, but this is a new problem for me because I just need the data – Vincent Nguyen Jun 01 '18 at 15:39
  • Okay, I'm really close now. The only problem I have now is still, how do I return variable after `getResponse().then...` What I have is two `forEach` inside `getResponse().then(forEach...)` and I push to `stuff` but not sure how to return `stuff` outside the `then` it comes back as empty – Vincent Nguyen Jun 01 '18 at 16:04
  • Can't I return another promise with that variable and print in another function? – Vincent Nguyen Jun 01 '18 at 16:27
  • Never mind, I just used an index to catch the last iteration of the `forEach` and logged my final result there. Thanks for all your help – Vincent Nguyen Jun 01 '18 at 16:33