Skip to content

Instantly share code, notes, and snippets.

@anemochore
Created December 19, 2019 01:49
Show Gist options
  • Save anemochore/0c533f06ac5ae6fea32f2589af31926d to your computer and use it in GitHub Desktop.
Save anemochore/0c533f06ac5ae6fea32f2589af31926d to your computer and use it in GitHub Desktop.
legacy pattern by me for async fetching multiple urls
(function() {
var inputUrls = ['https://same.origin.pages', ...]; //input
var result = []; //global var for output
getTextFromUrls(inputUrls);
function getTextFromUrls(urlArray) {
var urls = urlArray.slice();
asyncFetch(urls.pop());
function asyncFetch(url) {
console.log(url);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState==4 && xhr.status==200)
fetchSuccess(xhr.responseText); //no error-handling for brevity
};
xhr.open('GET', url);
xhr.send();
}
function fetchSuccess(txt) {
result.push(txt.slice(0, 256)); //processing response
if(urls.length == 0)
loadEnd();
else
asyncFetch(urls.pop());
}
}
function loadEnd() {
console.log('done!');
console.log(result);
//or another entry point
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment