1

I am trying to get data from an axios request in a foreach loop, but every time it is undefined. If I move the console.log inside the .then function, it works, but after the loop, it returns empty array. I did find, that it is reentering loop, before it saves to the array. How would I fix that?

var temp = [];

for(var route of coordinates) {
  axios('https://api.openweathermap.org/data/2.5/weather?lat=' + route.position.latitude + '&lon=' + route.position.longitude + '&units=metric&appid=39f1004c7ecc22d6f734974c44428625')
  .then((response)=>{
    temp.push({lat: route.position.latitude, lon: route.position.longitude, temp: Math.round(response.data.main.temp)});
  })
  .catch((error)=>{
    console.log(error)
  })
}

console.log(temp);
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – zero298 Jan 10 '20 at 16:05

1 Answers1

0

Try to read and understand this:
(https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Introducing)


Until then, look at this code below. The console log within the loop will hold on showing temp until the last axios response within the last iteration.

var temp = [];
let idx = coordinates.length;

for (var route of coordinates) {

    axios('https://api.openweathermap.org/data/2.5/weather?lat=' + route.position.latitude + '&lon=' + route.position.longitude + '&units=metric&appid=39f1004c7ecc22d6f734974c44428625')
        .then((response) => {
            temp.push({ lat: route.position.latitude, lon: route.position.longitude, temp: Math.round(response.data.main.temp) });

            // if this is the last iteration show temp
            if (!--idx) {
                console.log(temp);
            }

        })
        .catch((error) => {
            console.log(error)
        })

}

// this won't wait for axios calls so temp is empty
console.log(temp);
Alex Baban
  • 11,312
  • 4
  • 30
  • 44