0

Here is just a small piece of code to illustrate my problem. I want to store the data in the state object and access the data through the state object. But when I log the state object to the console I see all the data, when trying to access the data properties I get an undefined?

var state = {}
var weather = new Weather('Boston')

var getResults = async () => {
    await weather.getData()
    console.log(weather)
    state.result = weather
}
getResults()

console.log(state)        ------------------> logs all the data
console.log(state.result)   ------------------> undefined
Noud
  • 55
  • 9
  • 1
    `getResults` is async. You can't read the values it sets until after it has run. (`console.log` has lazy evaluation of objects, it doesn't check the contents of the object you are logging until you explicitly look at it (which will be after the async function has finished). – Quentin Jan 13 '20 at 11:06
  • It should be console.log(state.result) . ??? – tanuj upreti Jan 13 '20 at 11:12
  • Also what @Quentin said above. getResults itself is asynchronous in nature. So firstly that should be executed and then you must console.log – tanuj upreti Jan 13 '20 at 11:14
  • You are right should be state.result but that doesn't solve the issue. – Noud Jan 13 '20 at 11:22
  • It works like this: getResults().then( result => console.log(state.result.data)) Or when logging it within the async function. You can only process the data within the async functions body or in the then() callback – Noud Jan 13 '20 at 14:41

0 Answers0