Created
December 19, 2019 01:49
-
-
Save anemochore/0c533f06ac5ae6fea32f2589af31926d to your computer and use it in GitHub Desktop.
legacy pattern by me for async fetching multiple urls
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() { | |
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