2016-10-21 06:42:17 +00:00
|
|
|
'use strict';
|
2019-03-12 08:17:11 +00:00
|
|
|
|
2016-10-21 06:42:17 +00:00
|
|
|
class TimeoutError extends Error {
|
|
|
|
constructor(message) {
|
|
|
|
super(message);
|
2017-05-14 14:59:23 +00:00
|
|
|
this.name = 'TimeoutError';
|
2016-10-21 06:42:17 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-01 15:40:53 +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
|
|
|
}
|
|
|
|
|
2019-09-17 15:09:28 +00:00
|
|
|
if (milliseconds === Infinity) {
|
|
|
|
resolve(promise);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2020-12-01 15:40:53 +00:00
|
|
|
options = {
|
|
|
|
customTimers: {setTimeout, clearTimeout},
|
|
|
|
...options
|
|
|
|
};
|
|
|
|
|
|
|
|
const timer = options.customTimers.setTimeout(() => {
|
2016-10-21 06:42:17 +00:00
|
|
|
if (typeof fallback === 'function') {
|
2017-11-28 20:05:54 +00:00
|
|
|
try {
|
|
|
|
resolve(fallback());
|
2019-03-12 08:17:11 +00:00
|
|
|
} catch (error) {
|
|
|
|
reject(error);
|
2017-11-28 20:05:54 +00:00
|
|
|
}
|
2019-03-12 08:17:11 +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`;
|
2019-03-12 08:17:11 +00:00
|
|
|
const timeoutError = fallback instanceof Error ? fallback : new TimeoutError(message);
|
2016-10-21 06:42:17 +00:00
|
|
|
|
2017-11-19 09:33:44 +00:00
|
|
|
if (typeof promise.cancel === 'function') {
|
|
|
|
promise.cancel();
|
|
|
|
}
|
|
|
|
|
2019-03-12 08:17:11 +00:00
|
|
|
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-01 15:40:53 +00:00
|
|
|
options.customTimers.clearTimeout(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
|
|
|
});
|
|
|
|
|
2019-03-12 08:17:11 +00:00
|
|
|
module.exports = pTimeout;
|
2019-04-04 04:58:41 +00:00
|
|
|
// TODO: Remove this for the next major release
|
2019-03-12 08:17:11 +00:00
|
|
|
module.exports.default = pTimeout;
|
|
|
|
|
2016-10-21 06:42:17 +00:00
|
|
|
module.exports.TimeoutError = TimeoutError;
|