Skip to content

Instantly share code, notes, and snippets.

@dannycroft
Last active January 2, 2016 02:19
Show Gist options
  • Select an option

  • Save dannycroft/8236174 to your computer and use it in GitHub Desktop.

Select an option

Save dannycroft/8236174 to your computer and use it in GitHub Desktop.
/**
* Get content from a URL (e.g. JavaScript) using RSVP promises
*/
var getUrl = function (url) {
var xhr = new XMLHttpRequest();
// @see https://github.com/tildeio/rsvp.js
var promise = new RSVP.Promise();
xhr.open('GET', url);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
promise.resolve(xhr.responseText);
} else {
promise.reject(new Error(xhr.statusText));
}
}
};
xhr.send();
return promise;
};
/**
* getUrl usage with chained call backs
*/
getUrl(url).then(function (text) {
// Do something with URL responseText
return text;
}).catch (function (error) {
// Handle errors
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment