Last active
July 1, 2022 23:35
-
-
Save davej/728b20518632d97eef1e5a13bf0d05c7 to your computer and use it in GitHub Desktop.
Add a pseudo timeout/deadline to a request using the ES6 fetch 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
Promise.race([ | |
fetch('/foo'), | |
new Promise((_, reject) => | |
setTimeout(() => reject(new Error('Timeout')), 7000) | |
) | |
]); |
👏
🙌
👍
This does not cancel the (hanging) request. Use this solution instead: https://stackoverflow.com/a/57888548/13037768.
const fetchTimeout = (url, ms, { signal, ...options } = {}) => {
const controller = new AbortController();
const promise = fetch(url, { signal: controller.signal, ...options });
if (signal) signal.addEventListener("abort", () => controller.abort());
const timeout = setTimeout(() => controller.abort(), ms);
return promise.finally(() => clearTimeout(timeout));
};
Not supported in Internet Explorer (it is in Edge). See https://developer.mozilla.org/en-US/docs/Web/API/AbortController#Browser_compatibility
Not supported in Internet Explorer (it is in Edge).
ppl should stop supporting IE
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Promise.race: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/race
fetch: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch