Exploring the world of asynchronous JavaScript, I find myself pondering a question: how can I ensure that my code only starts working on a created array once all queries are completed? My current approach involves fetching pages in a for loop. Here's a snippet of my code:
var allOrgReposData = [];
var repoContributorsUrls = [];
for (var i=1; i <= orgPageIterations; i++) {
var orgReposUrl = 'https://api.github.com/orgs/angular/repos?page='+i;
fetch(orgReposUrl)
.then(response => response.json())
.then(orgReposData => {
allOrgReposData = allOrgReposData.concat(orgReposData);
console.log(allOrgReposData);
})
}
In this code snippet, you'll notice that the allOrgReposData array is being populated within the for loop. However, any operations I try to perform on this array end up being multiplied with each iteration, leading to unexpected results. For example, with 30 items per page, I see calculations like 30; 60; 90; 120; 150; 171 equating to 621 instead of the expected 171.
Is there a way to pause execution until all data is fetched and avoid this "multiplication" effect?
Warm regards!