Created
May 11, 2020 21:50
-
-
Save aredridel/c29cb2adf50eda6f627b9201f5bb9973 to your computer and use it in GitHub Desktop.
fetch jsonp with a modern API
This file contains 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
/** | |
* @param {string} url | |
*/ | |
function fetchJSONP(url) { | |
return new Promise((accept, reject) => { | |
const req = `jsonp${String(Math.random()).replace(".", "_")}`; | |
const scr = document.createElement("script"); | |
scr.src = url + `&callback=${req}`; | |
scr.onerror = cleanup; | |
document.head.append(scr); | |
const timeout = setTimeout(() => { | |
cleanup(); | |
reject(new Error("Timeout")); | |
}, 5000); | |
/// @ts-ignore | |
window[req] = data => { | |
cleanup(); | |
accept(data); | |
}; | |
function cleanup() { | |
/// @ts-ignore | |
delete window[req]; | |
clearTimeout(timeout); | |
scr.remove(); | |
} | |
}); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment