I'm having trouble understanding where my for loop needs to go if I'm fetching with it. I have code that is dependent on all the promises being resolved and JSON data being saved to testarray
I have created a variety of attempts, but they don't solve my problem. One is to for loop the call to a function which has a promise within it.
function getData() {
return new Promise(function (resolve, reject) {
fetch(url[i])
.then((resp) => resp.json())
.then(function (data) {
buffer = data;
resolve();
});
});
}
for (i = 0; i <2; i++){
getData().then(function(){
testarray.push(buffer);
//do stuff with testarray
})
}
but this doesn't work because I cant use the data that is pushed on testarray
, unless its in the for loop block.
If I put the for loop around the promise or around the fetch, I have a similar problem.
So my question is. If you use a for loop to fetch a variety of JSONs with an API call, how do you use the data outside the for loop? The actions I need for the data require all of it to be done.
I'm confused because I feel like Javascript is forcing me to put the action or code associated with the data where my comment is. Is this normal?