Last active
August 20, 2018 18:37
-
-
Save djp424/a02c4770753baf0accb443bfe6859b78 to your computer and use it in GitHub Desktop.
Asynchronous fetch JSON data from URLs with Promises (XMLHttpRequest)
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
// 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