Created
June 28, 2014 16:27
-
-
Save venuatu/308c615b7f2c3f7aa198 to your computer and use it in GitHub Desktop.
JSONP in an ES6 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
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