2016-10-21 06:42:17 +00:00
|
|
|
'use strict';
|
2017-06-27 14:41:26 +00:00
|
|
|
const delay = require('delay');
|
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-05-14 15:03:00 +00:00
|
|
|
if (typeof ms !== 'number' && ms >= 0) {
|
|
|
|
throw new TypeError('Expected `ms` to be a positive number');
|
2016-10-21 06:42:17 +00:00
|
|
|
}
|
|
|
|
|
2017-06-27 14:41:26 +00:00
|
|
|
delay(ms).then(() => {
|
2016-10-21 06:42:17 +00:00
|
|
|
if (typeof fallback === 'function') {
|
|
|
|
resolve(fallback());
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const message = typeof fallback === 'string' ? fallback : `Promise timed out after ${ms} milliseconds`;
|
|
|
|
const err = fallback instanceof Error ? fallback : new TimeoutError(message);
|
|
|
|
|
|
|
|
reject(err);
|
2017-06-27 14:41:26 +00:00
|
|
|
});
|
|
|
|
promise.then(resolve, reject);
|
2016-10-21 06:42:17 +00:00
|
|
|
});
|
|
|
|
module.exports.TimeoutError = TimeoutError;
|