I need to load two json files and loop through them to extract the values I need. The first loop loads a file per page (in the code file1_page=${i}.json), which has contains id's that I would use to then load the information of the second file based on id. I then need to take the data I need from the second for loop and push it in to an array outside of the json objects. I understand that javaScript is asynchronous so it doesn't wait until the bit which pushes the array finishes before it outputs the array I want. I have managed to defer the issue using setTimeout although, the time to wait will vary depending on the size of the files so I cannot preset that to be sure that it will always wait for enough.
Therefore what I need is a way for the code to decide on it's own when the for loops are finished.
function update_league_picks (selected_league){
var league_picks = []
for (let i=1; i<=20;i++){
d3.json(`file1_page=${i}.json`, function(error, league_players) {
if (error) throw error;
var players_page = league_players["standings"]["results"]
var gw = 2
for (let j=0; j<players_page.length; j++){
team_id = players_page[j].entry
d3.json(`file2_id=${j}.json`, function(error, opp_data) {
if (error) throw error;
league_picks.push({"active_chip":opp_data.active_chip)
})
}
})
}
console.log(league_picks)
// setTimeout(function() {
// console.log(league_picks)
// }, 100000)
}