Created
December 11, 2015 12:15
-
-
Save weiland/9cd21a728ff0dca2ba5c to your computer and use it in GitHub Desktop.
JSONP with Promises
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
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