p-timeout/index.js

53 lines
1.2 KiB
JavaScript
Raw Normal View History

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