Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@djp424
Last active August 20, 2018 18:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save djp424/a02c4770753baf0accb443bfe6859b78 to your computer and use it in GitHub Desktop.
Save djp424/a02c4770753baf0accb443bfe6859b78 to your computer and use it in GitHub Desktop.
Asynchronous fetch JSON data from URLs with Promises (XMLHttpRequest)
// Get data from list of URL's in asynchronous.
function asyncRequester(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = () => resolve(xhr.responseText);
xhr.onerror = () => reject(xhr.statusText);
xhr.send();
});
}
var urls = ['temp.json', 'temp.json', 'temp.json', 'temp.json', 'temp.json'],
pall = [],
resu = document.querySelector('#results');
for(var i in urls) {
pall.push(asyncRequester(urls[i]));
}
Promise.all(pall).then(function(results) {
for(var i in results) {
var json = JSON.parse(results[i]),
li = document.createElement('li'),
text = document.createTextNode(json[0]['title']['rendered']);
li.appendChild(text);
resu.appendChild(li);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment