p-timeout/index.js

62 lines
1.3 KiB
JavaScript
Raw Normal View History

2016-10-21 06:42:17 +00:00
'use strict';
2016-10-21 06:42:17 +00:00
class TimeoutError extends Error {
constructor(message) {
super(message);
this.name = 'TimeoutError';
2016-10-21 06:42:17 +00:00
}
}
const pTimeout = (promise, milliseconds, fallback, options) => new Promise((resolve, reject) => {
2019-03-12 08:21:47 +00:00
if (typeof milliseconds !== 'number' || milliseconds < 0) {
throw new TypeError('Expected `milliseconds` to be a positive number');
2016-10-21 06:42:17 +00:00
}
if (milliseconds === Infinity) {
resolve(promise);
return;
}
options = {
customTimers: {setTimeout, clearTimeout},
...options
};
2020-12-06 09:12:12 +00:00
const timer = options.customTimers.setTimeout.call(undefined, () => {
2016-10-21 06:42:17 +00:00
if (typeof fallback === 'function') {
2017-11-28 20:05:54 +00:00
try {
resolve(fallback());
} catch (error) {
reject(error);
2017-11-28 20:05:54 +00:00
}
2016-10-21 06:42:17 +00:00
return;
}
2019-03-12 08:21:47 +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();
}
reject(timeoutError);
2019-03-12 08:21:47 +00:00
}, milliseconds);
2016-10-21 06:42:17 +00:00
2020-12-01 15:50:36 +00:00
(async () => {
try {
resolve(await promise);
} catch (error) {
reject(error);
} finally {
2020-12-06 09:12:12 +00:00
options.customTimers.clearTimeout.call(undefined, timer);
2016-10-21 06:42:17 +00:00
}
2020-12-01 15:50:36 +00:00
})();
2016-10-21 06:42:17 +00:00
});
module.exports = pTimeout;
// TODO: Remove this for the next major release
module.exports.default = pTimeout;
2016-10-21 06:42:17 +00:00
module.exports.TimeoutError = TimeoutError;