Skip to content

Instantly share code, notes, and snippets.

@macndesign
Last active July 22, 2016 17:45
Show Gist options
  • Save macndesign/b7b24e5e4f0d0325b73bd0284def696a to your computer and use it in GitHub Desktop.
Save macndesign/b7b24e5e4f0d0325b73bd0284def696a to your computer and use it in GitHub Desktop.
/* CREDIT - Jake Archibald, http://www.html5rocks.com/en/tutorials/es6/promises/ */
function get(url) {
return new Promise(function(resolve, reject) {
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
if (req.status == 200) {
resolve(req.response); /* PROMISE RESOLVED */
} else {
reject(Error(req.statusText)); /* PROMISE REJECTED */
}
};
req.onerror = function() {
reject(Error("Network Error"));
};
req.send();
});
}
// Get JSON Helper
function getJSON(url) {
return get(url).then(JSON.parse);
}
// Getting a list o items at specific resource
var data = getJSON('http://localhost:8000/api/blog/posts/')
.then(function(response) {
// Getting and load content for next page
return getJSON(response.next);
}).then(function(response) {
// Return results in JSON at page 2
return response.results;
}).catch(function(err) {
console.log(err);
});
// Getting 3 URLs from specific resource and load your contents in parallel
// and if all is loaded, return all contents.
var allContents = getJSON('http://localhost:8000/api/blog/')
.then(function(response) {
// Making array of specific URLs
var urls = [response.posts, response.authors, response.tags];
// Loading contents in parallel via XHR and making an array of Promises
var pUrls = urls.map(getJSON);
// Using Promise.all to return all after load all contents
var pContents = Promise.all(pUrls)
.then(function(arrayOfResults) {
return arrayOfResults;
}).catch(function(err) {
console.log(err);
});
return pContents;
}).then(function(response){
return response;
}).catch(function(err) {
console.log(err)
});
/* View: https://bitsofco.de/javascript-promises-101/ */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment