Skip to content

Instantly share code, notes, and snippets.

@singh-shweta
Created January 27, 2022 19:23
Show Gist options
  • Save singh-shweta/124f7ea7b62d517c117d4962b8ec4edc to your computer and use it in GitHub Desktop.
Save singh-shweta/124f7ea7b62d517c117d4962b8ec4edc to your computer and use it in GitHub Desktop.
A javascript implementation of fetchAll without using Promises
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 (let 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