Instantly share code, notes, and snippets.

Embed
What would you like to do?
fetch timeout
const CONNECTION_TIMEOUT = 20000;
function getData (url) {
let timer = null;
const service = fetch(url)
.then((response) => {
clearTimeout(timer);
return response.json();
});
const timeout = new Promise((resolve) => { timer = setTimeout(resolve, CONNECTION_TIMEOUT); })
.then(() => { throw new Error('Connection timeout'); });
return Promise.race([service, timeout]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment