Skip to content

Instantly share code, notes, and snippets.

@aredridel
Created May 11, 2020 21:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aredridel/c29cb2adf50eda6f627b9201f5bb9973 to your computer and use it in GitHub Desktop.
Save aredridel/c29cb2adf50eda6f627b9201f5bb9973 to your computer and use it in GitHub Desktop.
fetch jsonp with a modern API
/**
* @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