Created
February 3, 2022 09:29
-
-
Save singh-shweta/fbd1752327c4bfc049db0e1aa460c745 to your computer and use it in GitHub Desktop.
fetchAll method working fine with closure
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; | |
var callbackFunctionAfterFetch= function(i) { | |
return function (response) { | |
if (response) { | |
responsesArray[i] = response; | |
console.log("resolved url --->", urls[i]); | |
callbacksCount++; | |
if (callbacksCount === urls.length) { | |
callback(responsesArray); | |
} | |
} | |
}; | |
} | |
for (var i = 0; i < urls.length; i++) { | |
fetchData(urls[i], callbackFunctionAfterFetch(i)); | |
} | |
} | |
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