p-timeout/index.js

64 lines
1.4 KiB
JavaScript
Raw Normal View History

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);
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) {
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) {
resolve(promise);
return;
}
options = {
customTimers: {setTimeout, clearTimeout},
...options
};
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
}
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
if (typeof promise.cancel === 'function') {
promise.cancel();
}
2016-10-21 06:42:17 +00:00
reject(timeoutError);
}, milliseconds);
(async () => {
try {
resolve(await promise);
} catch (error) {
reject(error);
} finally {
options.customTimers.clearTimeout.call(undefined, timer);
}
})();
});
cancelablePromise.clear = () => {
clearTimeout(timer);
timer = undefined;
};
2016-10-21 06:42:17 +00:00
return cancelablePromise;
2021-04-06 17:38:12 +00:00
}