Skip to content

Instantly share code, notes, and snippets.

@chrisl8
Created September 17, 2015 21:37
Show Gist options
  • Save chrisl8/8d4a6882123de89bda4a to your computer and use it in GitHub Desktop.
Save chrisl8/8d4a6882123de89bda4a to your computer and use it in GitHub Desktop.
Simple Promise example from the web
// Source: https://gist.github.com/domenic/3889970
// Just sticking the parts in one spot and playing with them.
function getTweetsFor() {
var ajaxOptions = {
url: '...',
...
};
return new RSVP.Promise(function(resolve, reject) {
ajaxOptions.success = function(json) { resolve(json); };
ajaxOptions.error = function(jqXHR) {
if (jqXHR && typeof jqXHR === 'object') {
jqXHR.then = null;
}
reject(jqXHR);
}
$.ajax(ajaxOptions);
});
}
getTweetsFor("domenic") // promise-returning async function
.then(function (tweets) {
var shortUrls = parseTweetsForUrls(tweets);
var mostRecentShortUrl = shortUrls[0];
return expandUrlUsingTwitterApi(mostRecentShortUrl); // promise-returning async function
})
.then(doHttpRequest) // promise-returning async function
.then(
function (responseBody) {
console.log("Most recent link text:", responseBody);
},
function (error) {
console.error("Error with the twitterverse:", error);
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment