I'm currently trying to empty an array and then fill it with information grabbed from an API upon every iteration that the overlying function is called for, all in JavaScript.
function getInfo() {
clearArray()
// call the API
callAPI()
// push arrayObjects into DOM
array.forEach(object => {
// do stuff with it
}
}
clearArray() sets the length of the array to zero:
function clearArray() {
array.length = 0
}
callAPI() is a fetch function:
function callAPI() {
fetch(urlG)
.then(response => response.json())
.then(function(response) {
// parse and then push objects into global array
})
}
I'm pretty sure that the callAPI() function is doing it's job correctly from console.log()-ing at various points.
However, when I console.log(array.length) right before the forEach statement, it turns up to be 0. I read that console.log may not be the most accurate in this case, but:
- Adding a console.log(array) right after the clearArray() function - but before callAPI() - prints out the correctly filled out array in the console.
- Same thing for adding the console.log(array) after callAPI() is called.
- console.log(array.length) anywhere results in 0.
- Using breakpoints before and after each function is called always shows the array being empty.
I tried using a callback to force it to wait, like this:
callAPI(callback)
function callAPI(callback) {
fetch(url)
.then(response => response.json())
.then(function(response) {
// do stuff
})
callback()
}
getInfo():
function getInfo() {
// reset news array
clearArray()
// call the news APIs
callAPI(function() {
console.log(array.length)
// push arrayObjects into DOM
array.forEach(arrayObject => {
// do stuff
})
}
}
But I'm running into the same error.
Using await
for fetch(url) ends up in the same exact issue.
async function callAPI() {
let response = await fetch(url)
let json = response.json()
let results = json.response.results
// do stuff
}
I'm still relatively unfamiliar with JavaScript, so if any further information is needed then I can absolutely supply it.