Skip to content

Instantly share code, notes, and snippets.

@singh-shweta
Created February 3, 2022 07:53
Show Gist options
  • Save singh-shweta/39fec2e1f7d77a0860a7bba6216110fa to your computer and use it in GitHub Desktop.
Save singh-shweta/39fec2e1f7d77a0860a7bba6216110fa to your computer and use it in GitHub Desktop.
Fetch All using var- the behavior
function fetchData(url, c) {
console.log("url====", url);
setTimeout(function () {
console.log("===in fetchdata callback for url===", url);
return c("response" + url);
}, 100 * url.length);
}
function fetchAll(urls, callback) {
/* responsesArray contains reponses index wise*/
let responsesArray = [];
/* callbacksCount contains hom many times the callback has been called */
let callbacksCount = 0;
for (var i = 0; i < urls.length; i++) {
fetchData(urls[i], function (response) {
if (response) {
responsesArray[i] = response;
console.log("resolved url --->", urls[i]);
callbacksCount++;
if (callbacksCount === urls.length) {
callback(responsesArray);
}
}
});
}
}
fetchAll(["ar", "brty", "c"], function (responses) {
console.log("responses are ------> ", responses);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment