2016-10-21 06:42:17 +00:00
|
|
|
'use strict';
|
2019-03-12 08:17:11 +00:00
|
|
|
|
2017-07-02 01:41:51 +00:00
|
|
|
const pFinally = require('p-finally');
|
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
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-03-12 08:21:47 +00:00
|
|
|
const pTimeout = (promise, milliseconds, fallback) => 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
|
|
|
}
|
|
|
|
|
|
|
|
const timer = setTimeout(() => {
|
|
|
|
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
|
|
|
|
2019-03-12 08:21:47 +00:00
|
|
|
// TODO: Use native `finally` keyword when targeting Node.js 10
|
2017-07-02 01:41:51 +00:00
|
|
|
pFinally(
|
2019-03-12 08:17:11 +00:00
|
|
|
// eslint-disable-next-line promise/prefer-await-to-then
|
2017-07-02 01:41:51 +00:00
|
|
|
promise.then(resolve, reject),
|
|
|
|
() => {
|
2016-10-21 06:42:17 +00:00
|
|
|
clearTimeout(timer);
|
|
|
|
}
|
|
|
|
);
|
|
|
|
});
|
|
|
|
|
2019-03-12 08:17:11 +00:00
|
|
|
module.exports = pTimeout;
|
|
|
|
module.exports.default = pTimeout;
|
|
|
|
|
2016-10-21 06:42:17 +00:00
|
|
|
module.exports.TimeoutError = TimeoutError;
|