I am a JavaScript newbie and have a problem regarding an AJAX call to a local JSON file and afterwards accessing elements of the resulting data array. I fetch values called "number" from a local JSON file and put them in an array. My problem is: I can perfectly well log the whole array, but not single array values with "data[0]".
After a long search I am now pretty sure that it is an AJAX problem because I can log the element if I put the logging function into a setTimeout. I thought the async-await part would solve this, but apparently it does not. I have tried to use the "return new Promise((resolve, reject) => { ..." syntax in makeDataArray() instead, but it doesn't work either. I don't understand why the await-keyword does not wait "long enough" for the makeDataArray() function to finish. Can someone please explain this to me?
In case this is important: I am not allowed to use jQuery, which is why I use the asycn-await construct.
This is the JavaScript:
async function makeDataArray() {
var myNumbers = new Array();
fetch('../data/someNumbers.json')
.then(response => response.json())
.then(data => {
data.forEach(element =>{
myNumbers.push(element.number);
})
})
return myNumbers;
}
async function printArrayElements(){
let data = await makeDataArray();
console.log(data); //works correctly
console.log(data[0]); //undefined
setTimeout(function(){
console.log(data[0]);}, //works correctly
3000);
}
printArrayElements();
This is the JSON file:
[{
"number": 10
},
{
"number": 20
},
{
"number": 30
}
]