-
-
Save dtmrc/49f31271979e32a705ce76da4503b0a1 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 hidden or 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) | |
) | |
]); |
Handling timeout in Axios
https://medium.com/@masnun/handling-timeout-in-axios-479269d83c68
Abu Ashraf Masnun Jun 17, 2019
If you’re making http requests using the axios library on a browser or in a node app, do make sure that you have a timeout set. The default timeout is set to 0 which indicates no timeout. With that default value, any remote end can keep us waiting for the requested resource for an indefinite period. With limited resources at hand, we really wouldn’t like that to happen. Let’s set a timeout instead.
the error code, error message and the stack trace. It looks something like this:
ECONNABORTED
timeout of 2ms exceeded
Error: timeout of 2ms exceeded
at createError (/Users/masnun/Projects/medium/node_modules/axios/lib/core/createError.js:16:15)
at Timeout.handleRequestTimeout (/Users/masnun/Projects/medium/node_modules/axios/lib/adapters/http.js:252:16)
at listOnTimeout (timers.js:324:15)
at processTimers (timers.js:268:5)
— Set the value to
timeout
in a config object
— Timeout values are in milliseconds,{ timeout: 2 }
means 2ms timeout, not 2s.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
via @davej
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
via @maurits-tellow
This does not cancel the (hanging) request. Use this solution instead: https://stackoverflow.com/a/57888548/13037768.
Not supported in Internet Explorer (it is in Edge). See https://developer.mozilla.org/en-US/docs/Web/API/AbortController#Browser_compatibility