Skip to content

Instantly share code, notes, and snippets.

@venuatu
Created June 28, 2014 16:27
Show Gist options
  • Save venuatu/308c615b7f2c3f7aa198 to your computer and use it in GitHub Desktop.
Save venuatu/308c615b7f2c3f7aa198 to your computer and use it in GitHub Desktop.
JSONP in an ES6 promise
var jsonp = (function (window) {
var CALLBACK_CHARS = 'abcdefghijklmnopqrstuvwxyz0123456789';
return function jsonp(url, options) {
options = options || {};
options.timeout = options.timeout || 5000;
return new Promise(function (resolve, reject) {
var callback;
while (!callback || window[callback] !== undefined) {
callback = 'JSONP_';
for (var i = 0; i < 10; i++) {
callback += CALLBACK_CHARS[Math.random() * CALLBACK_CHARS.length | 0];
}
}
var script = document.createElement('script');
script.src = url + callback;
document.body.appendChild(script);
function cleanup() {
delete window[callback];
script.remove();
}
var ticket = setTimeout(function () {
reject('no response');
cleanup();
}, options.timeout);
window[callback] = function (data) {
resolve(data);
clearTimeout(ticket);
cleanup();
};
});
}
})(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment