1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-11-29 23:58:06 +01:00
metamask-extension/shared/modules/fetch-with-timeout.js

31 lines
742 B
JavaScript
Raw Normal View History

import { memoize } from 'lodash';
import { SECOND } from '../constants/time';
const getFetchWithTimeout = memoize((timeout = SECOND * 30) => {
if (!Number.isInteger(timeout) || timeout < 1) {
throw new Error('Must specify positive integer timeout.');
}
2020-11-03 00:41:28 +01:00
return async function _fetch(url, opts) {
const abortController = new window.AbortController();
const { signal } = abortController;
const f = window.fetch(url, {
...opts,
2020-12-23 17:15:07 +01:00
signal,
});
const timer = setTimeout(() => abortController.abort(), timeout);
try {
const res = await f;
clearTimeout(timer);
return res;
} catch (e) {
clearTimeout(timer);
throw e;
}
};
});
export default getFetchWithTimeout;