2021-04-06 17:38:12 +00:00
|
|
|
export class TimeoutError extends Error {
|
2016-10-21 06:42:17 +00:00
|
|
|
constructor(message) {
|
|
|
|
super(message);
|
2017-05-14 14:59:23 +00:00
|
|
|
this.name = 'TimeoutError';
|
2016-10-21 06:42:17 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-04-06 17:38:12 +00:00
|
|
|
export default function pTimeout(promise, milliseconds, fallback, options) {
|
2020-12-26 10:42:06 +00:00
|
|
|
let timer;
|
|
|
|
const cancelablePromise = new Promise((resolve, reject) => {
|
|
|
|
if (typeof milliseconds !== 'number' || milliseconds < 0) {
|
|
|
|
throw new TypeError('Expected `milliseconds` to be a positive number');
|
|
|
|
}
|
2016-10-21 06:42:17 +00:00
|
|
|
|
2021-04-06 17:38:12 +00:00
|
|
|
if (milliseconds === Number.POSITIVE_INFINITY) {
|
2020-12-26 10:42:06 +00:00
|
|
|
resolve(promise);
|
|
|
|
return;
|
|
|
|
}
|
2019-09-17 15:09:28 +00:00
|
|
|
|
2020-12-26 10:42:06 +00:00
|
|
|
options = {
|
|
|
|
customTimers: {setTimeout, clearTimeout},
|
|
|
|
...options
|
|
|
|
};
|
2020-12-01 15:40:53 +00:00
|
|
|
|
2020-12-26 10:42:06 +00:00
|
|
|
timer = options.customTimers.setTimeout.call(undefined, () => {
|
|
|
|
if (typeof fallback === 'function') {
|
|
|
|
try {
|
|
|
|
resolve(fallback());
|
|
|
|
} catch (error) {
|
|
|
|
reject(error);
|
|
|
|
}
|
|
|
|
|
|
|
|
return;
|
2017-11-28 20:05:54 +00:00
|
|
|
}
|
2019-03-12 08:17:11 +00:00
|
|
|
|
2020-12-26 10:42:06 +00:00
|
|
|
const message = typeof fallback === 'string' ? fallback : `Promise timed out after ${milliseconds} milliseconds`;
|
|
|
|
const timeoutError = fallback instanceof Error ? fallback : new TimeoutError(message);
|
2016-10-21 06:42:17 +00:00
|
|
|
|
2020-12-26 10:42:06 +00:00
|
|
|
if (typeof promise.cancel === 'function') {
|
|
|
|
promise.cancel();
|
|
|
|
}
|
2016-10-21 06:42:17 +00:00
|
|
|
|
2020-12-26 10:42:06 +00:00
|
|
|
reject(timeoutError);
|
|
|
|
}, milliseconds);
|
|
|
|
|
|
|
|
(async () => {
|
|
|
|
try {
|
|
|
|
resolve(await promise);
|
|
|
|
} catch (error) {
|
|
|
|
reject(error);
|
|
|
|
} finally {
|
|
|
|
options.customTimers.clearTimeout.call(undefined, timer);
|
|
|
|
}
|
|
|
|
})();
|
|
|
|
});
|
2017-11-19 09:33:44 +00:00
|
|
|
|
2020-12-26 10:42:06 +00:00
|
|
|
cancelablePromise.clear = () => {
|
|
|
|
clearTimeout(timer);
|
|
|
|
timer = undefined;
|
|
|
|
};
|
2016-10-21 06:42:17 +00:00
|
|
|
|
2020-12-26 10:42:06 +00:00
|
|
|
return cancelablePromise;
|
2021-04-06 17:38:12 +00:00
|
|
|
}
|