Last active
August 29, 2015 13:56
-
-
Save rwjblue/8929527 to your computer and use it in GitHub Desktop.
RSVP Promises
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
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 | |
}); |
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 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 | |
}); |
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
// 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