Created
January 27, 2022 19:23
-
-
Save singh-shweta/124f7ea7b62d517c117d4962b8ec4edc to your computer and use it in GitHub Desktop.
A javascript implementation of fetchAll without using Promises
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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