0
const data=[];
async function getData(){

   

 response= await fetch(url);
 jData= await response.json();

 for(var i in jData[1].state_data)
    data.push(jData[1].state_data[i]);

console.log(data);//FIRST CONSOLE LOG


}
getData();

console.log(data);//SECOND CONSOLE LOG

I want to insert the objects into an array that can be used elsewhere. But the second console.log is giving me an empty array. I do understand that it has something to do with global and local allocation but I can't seem to solve this issue.

NewJava
  • 7
  • 4
  • The second console log will fire fire cause javascript will run every code that is outside a function before executing the function – rocky Jul 14 '20 at 15:46
  • how do make it wait for the data to be filled inside? – NewJava Jul 14 '20 at 15:49
  • first, declare all your variables or they'll end up on the global scope. Then don't update/use the data-array at all, `return jData[1].state_data`. And at last, check out [promise.then()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) and [await promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await). – Thomas Jul 14 '20 at 15:54
  • The question should be, how do you debug that the api returned the expected data. firstly, use `let response = await fetch(url); let jData= await response.json(); ` now ensure the `jData ` has content by running `console.log(jData);` and finally, make sure the loop has the data you want to push by running `console.log(jData[1].state_data[i])` inside the loop. Once you are done merge the entire code and remove the console messages. :) – rocky Jul 14 '20 at 15:56
  • actually, the api is returning perfect data. I tested it using postman and the first console.log is giving me proper results. but the result is temporary and just inside the function. The data array is still unchanged and empty when i check it outside the function – NewJava Jul 14 '20 at 16:13

0 Answers0