Timing Out Fetch API Requests
Provide a way to timeout and abort Fetch API requests if the response from a cross-origin server takes too long.
const fetchWithTimeout = (resource, options = {}) => {
// Set a default timeout if not provided in the options
const { timeout = 5000 } = options;
// Create an AbortController instance
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeout);
// Include the signal from the controller in the options
const optionsWithSignal = { ...options, signal: controller.signal };
// Execute the fetch with the timeout and options including the abort signal
return fetch(resource, optionsWithSignal)
.then(response => {
// Clear the timeout as fetch has completed
clearTimeout(id);
return response;
})
.catch(error => {
// Clear the timeout in case of an error as well (e.g. aborted fetch)
clearTimeout(id);
// Propagate the error to be handled by the caller
throw error;
});
};
This function, fetchWithTimeout, wraps the Fetch API providing a way to specify a timeout duration. If the request takes longer than this duration, it will be aborted using an AbortController. The timeout can be specified via the options object. The fetch() call is returned with the abort signal included in the options, and any resulting errors are rethrown to be handled by the caller.