-
-
Save Atorui/6b1c67efbc382c2315201336fdd1c048 to your computer and use it in GitHub Desktop.
JSONP + Promise
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
| /* | |
| * From http://stackoverflow.com/a/22780569/141363 modified | |
| * to return Promise. | |
| * | |
| * Usage: jsonp(url) | |
| * .then(success) | |
| * .catch(error); | |
| */ | |
| var jsonp = (function(global, body) { | |
| 'use strict'; | |
| // Uses native Promise. Older browsers + IE11 and Safari 7 (!) need polyfill. | |
| if (!global.Promise) { | |
| throw 'Promise not available. Use a polyfill! http://promisesaplus.com/implementations'; | |
| } | |
| function createScript(url, callbackName) { | |
| var script = document.createElement('script'); | |
| script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + callbackName; | |
| return script; | |
| } | |
| return function(url) { | |
| return new Promise(function(resolve, reject) { | |
| var callbackName = 'jsonp_callback_' + Math.round(100000 * Math.random()), | |
| script = createScript(url, callbackName); | |
| // If we fail to get the script, reject the promise. | |
| script.onerror = reject; | |
| body.appendChild(script); | |
| // If the url contains a 'something_callback=?' then | |
| // replace the '?' with our random generated callbackName. | |
| if (/callback=?/.test(url)) { | |
| url = url.replace('=?', '=' + callbackName); | |
| } | |
| global[callbackName] = function(data) { | |
| // Script inserted, resolve promise. | |
| resolve(data); | |
| // Clean up. | |
| global[callbackName] = null; | |
| delete global[callbackName]; | |
| body.removeChild(script); | |
| }; | |
| }); | |
| }; | |
| }(this, document.body)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment