Missing timeout support
AjaxSolutions opened this issue · 5 comments
I don't see that the axios timeout config is supported.
Indeed, good catch.
@developit I think we can pick this up after request cancellation feature is done.
Since fetch does not support timeout (I don't know if fetch
does support timeout) out of the box (we can acheive via setTimeout
and AbortController
)
One way to implement this is when the timeout
is provided in the options
we'll create an AbortController and pass the singal to fetch and we'll set off a setTimeout
for the duration specified in the timeout option and inside the callback we'll abort
the signal.
But there is a catch, If cancelToken
option is also provided along with timeout
then we'll need to chain the signals (singal from cancelToken
& the signal that we will create for timeout) Refer this snippet for chaining of singals
and while passing singnal to fetch we'll have to do it this way I think
{ signal: timeoutAbortController.signal || options.cancelToken }
In the event when both cancelToken
& timeout
are provided higher precedence should be given to timeoutAbortController
because we'll have access to it's abort()
handle which will be required to cancel the fetch onTimeout or cancel being called externally.
I don't know if there is a simpler way to implement this, I'll be happy if there is a simpler way with less code.
I've also good experience of using AbortController. Here is a full code example of utility function implementing the timeout:
/**
Aborts fetch request after given time. Usage:
fetch('chatoptions/waittime', {
signal: abortFetchInSeconds(10)
})
@param { number } timeout - abort time (timeout) in seconds
@return AbortSignal|undefined - undefined is returned when browser does not support AbortController
*/
function abortFetchInSeconds(timeout) {
if (window.AbortController === undefined) {
return undefined;
}
const abortController = new AbortController();
setTimeout(() => abortController.abort(), timeout * 1000);
return abortController.signal;
}
For those who will come here, i'll leave examples of using type script code and code.
const fetchWithTimeout =
(timeoutMs: number) =>
(input: RequestInfo, init?: RequestInit): Promise<Response> => {
return fetch(input, {
...init,
signal: abortFetchSignal(timeoutMs),
})
}
const abortFetchSignal = (timeoutMs: number) => {
if (typeof window === 'undefined' || window.AbortController === undefined) {
return undefined
}
const abortController = new AbortController()
setTimeout(() => abortController.abort(), timeoutMs)
return abortController.signal
}
// Usage #1
redaxios.create({
fetch: fetchWithTimeout(1000),
})
// Usage #2
redaxios.get('~~', {
fetch: fetchWithTimeout(1000),
})
// Usage #3
export const axios = redaxios.create({
fetch: fetchWithTimeout(1000),
}) as typeof redaxios
hi, this is VERY useful feature, when this ll be supported in options?