@gluons/react-native-fetch-with-timeout
Version:
Fetch with timeout for React Native.
41 lines (40 loc) • 1.29 kB
JavaScript
/**
* Abort handler.
* Prevent error thrown when `fetch` aborted.
*
* @param err Error
* @returns Empty JSON response (`{}`)
*/
export const AbortHandler = (err) => {
if ((err === null || err === void 0 ? void 0 : err.name) === 'AbortError') {
return new Response('{}');
}
throw err;
};
/**
* `fetch` with timeout support.
*
* @param {RequestInfo} input Request info
* @param {RequestInit} init Request options
* @param {FetchWithTimeoutOptions} timeout `fetchWithTimeout`'s options
*/
export default async function fetchWithTimeout(input, init, options = {
timeout: false,
abortController: new AbortController(),
abortHandler: AbortHandler
}) {
const { timeout = false, abortController = new AbortController(), abortHandler = AbortHandler } = options;
init = Object.assign(Object.assign({}, init), { signal: abortController.signal });
if (!timeout) {
return fetch(input, init).catch(abortHandler);
}
return Promise.race([
fetch(input, init).catch(abortHandler),
new Promise((_, reject) => {
setTimeout(() => {
abortController.abort();
reject(new Error('Request Timeout'));
}, timeout);
})
]);
}