Last active
January 2, 2016 02:19
-
-
Save dannycroft/8236174 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| /** | |
| * 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