0

I have read through various posts regarding async/await but am still having trouble implementing this simple action.

const endpoint = 'http://api.openweathermap.org/data/2.5/weather?q=Oakland&APPID=54d05c3dfefbf06b604ba3ffcaaabdcf'

const weather = [];

fetch(endpoint)
    .then(response => response.json())
    .then(data => weather.push(...data));

console.log(weather)
// returns blank arr []

I just want to have my data in an array to work with. I believe this is because fetch is running before const weather is defined? If somebody could quickly tell me what to put where, I would be very thankful.

NOTE: I have read How do I return the response from an asynchronous call? and am still having issues.

Scott Ledbetter
  • 328
  • 1
  • 4
  • 9
  • Should probably be [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/q/23667086/4642212) instead. What remaining issues do you have? `fetch` does not run before `const weather` is defined. `console.log(weather)` runs before `data => weather.push(...data)`. – Sebastian Simon Jul 09 '18 at 00:42
  • Ok, so if I understand fetch starts running and then js tries to log it while that is happening. Then why won't doing a third then `.then(() => console.log(weather));` work? I want my weather array to be global and accessible after the fetch call. – Scott Ledbetter Jul 09 '18 at 00:55
  • It _would_ work, but not if you use [`.push`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) because it returns the new length of the array, not the array itself. Don’t use a global `weather`; you don’t need it. Instead of `.then(data => weather.push(...data))` just directly use `.then(weather => console.log(weather))`. You can’t really use the result of an async call “outside” or “after” the `fetch`. You could use the syntactic sugar of [`async`/`await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). – Sebastian Simon Jul 09 '18 at 01:01
  • Thanks for the help. So yes I can `console.log` the object, but that doesn't let me do anything useful with it. I need to have it in an accessible array so I can play with the data, and haven't found a way to do that! – Scott Ledbetter Jul 09 '18 at 01:06

0 Answers0