2016-10-21 06:42:17 +00:00
|
|
|
'use strict';
|
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
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = (promise, ms, fallback) => new Promise((resolve, reject) => {
|
2017-11-19 09:27:16 +00:00
|
|
|
if (typeof ms !== 'number' || ms < 0) {
|
2017-05-14 15:03:00 +00:00
|
|
|
throw new TypeError('Expected `ms` 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 (err) {
|
|
|
|
reject(err);
|
|
|
|
}
|
2016-10-21 06:42:17 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const message = typeof fallback === 'string' ? fallback : `Promise timed out after ${ms} milliseconds`;
|
|
|
|
const err = fallback instanceof Error ? fallback : new TimeoutError(message);
|
|
|
|
|
2017-11-19 09:33:44 +00:00
|
|
|
if (typeof promise.cancel === 'function') {
|
|
|
|
promise.cancel();
|
|
|
|
}
|
|
|
|
|
2016-10-21 06:42:17 +00:00
|
|
|
reject(err);
|
|
|
|
}, ms);
|
|
|
|
|
2017-07-02 01:41:51 +00:00
|
|
|
pFinally(
|
|
|
|
promise.then(resolve, reject),
|
|
|
|
() => {
|
2016-10-21 06:42:17 +00:00
|
|
|
clearTimeout(timer);
|
|
|
|
}
|
|
|
|
);
|
|
|
|
});
|
|
|
|
|
|
|
|
module.exports.TimeoutError = TimeoutError;
|