Skip to content

Instantly share code, notes, and snippets.

@weiland
Created December 11, 2015 12:15
Show Gist options
  • Save weiland/9cd21a728ff0dca2ba5c to your computer and use it in GitHub Desktop.
Save weiland/9cd21a728ff0dca2ba5c to your computer and use it in GitHub Desktop.
JSONP with Promises
const TIMEOUT = 10000;
function jsonp(url) {
return new Promise((resolve, reject) => {
let callbackName = 'jsonpCallback';
let timeoutTrigger = window.setTimeout(function(){
window[callbackName] = Function.prototype;
reject(new Error('Timeout'));
}, TIMEOUT);
window[callbackName] = function(data){
window.clearTimeout(timeoutTrigger);
resolve(data);
};
let script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = url;
document.getElementsByTagName('head')[0].appendChild(script);
});
}
export default jsonp;
// usage:
// jsonp('http://www.colourlovers.com/api/palettes/top?jsonCallback=jsonpCallback')
// .then(console.debug.bind(console, 'success'), console.error.bind(console, 'error'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment