Created
August 6, 2017 10:24
-
-
Save sobstel/ede78ad0bffc2efbcb49b93a152b838b to your computer and use it in GitHub Desktop.
fetch timeout
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
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