Skip to content

Instantly share code, notes, and snippets.

@rwjblue
Last active August 29, 2015 13:56
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 rwjblue/8929527 to your computer and use it in GitHub Desktop.
Save rwjblue/8929527 to your computer and use it in GitHub Desktop.
RSVP Promises
var promise = new Promise(function(resolve, reject) {
// on success
resolve(value);
// on failure
reject(reason);
});
promise.then(function(value) {
// on fulfillment
}, function(reason) {
// on rejection
});
function getJSON(url) {
return new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = handler;
xhr.responseType = 'json';
xhr.setRequestHeader('Accept', 'application/json');
xhr.send();
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error("getJSON: `" + url + "` failed with status: [" + this.status + "]");
}
}
};
});
}
getJSON('/posts.json').then(function(json) {
// on fulfillment
}, function(reason) {
// on rejection
});
// RSVP.Promise.all Example
var promises = [2, 3, 5, 7, 11, 13].map(function(id){
return getJSON("/post/" + id + ".json");
});
RSVP.all(promises).then(function(posts) {
// posts contains an array of results for the given promises
}).catch(function(reason){
// if any of the promises fails.
});
// RSVP.Promise.hash Example
var promises = {
posts: getJSON("/posts.json"),
users: getJSON("/users.json")
};
RSVP.hash(promises).then(function(results) {
console.log(results.users) // print the users.json results
console.log(results.posts) // print the posts.json results
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment