$ cnpm install @mrtnzlml/fetch
This package has been extracted from the original fbjs library and it exposes single fetchWithRetries
. This fetch solves two common problems:
yarn add @mrtnzlml/fetch
import fetchWithRetries from '@mrtnzlml/fetch';
fetchWithRetries('//localhost', {
// see: https://github.com/github/fetch/
// ...
fetchTimeout: 15000,
retryDelays: [1000, 3000],
})
.then(response => console.warn(response))
.catch(error => console.error(error));
It does two things:
Retries are performed in these situations:
fetchTimeout
) occursThis package uses fetch ponyfill internally (cross-fetch) so it supports server JS as well as browsers.
You have to catch errors while fetching the response. This fetch throws these exceptions:
Error
) when request failed for some reasonTimeoutError
when fetch fails because of defined timeoutResponseError
when final response returns HTTP status <200 or >=300Example:
import fetchWithRetries, {TimeoutError, ResponseError} from '@mrtnzlml/fetch';
(async () => {
try {
const response = await fetchWithRetries('//localhost');
// TODO: do something with the response
} catch (error) {
if (error instanceof TimeoutError) {
console.error('request timeouted');
} else if (error instanceof ResponseError) {
console.error('unsuccessful response', error.response);
} else {
console.error('unknown error');
}
}
})();
const config = {
fetchTimeout: 2000,
retryDelays: [100, 3000],
};
There are many situations that may occur (skipping happy path):
Example with timeouts:
Copyright 2014 - 2016 © taobao.org |