p-timeout/index.js

40 lines
810 B
JavaScript
Raw Normal View History

2016-10-21 06:42:17 +00:00
'use strict';
class TimeoutError extends Error {
constructor(message) {
super(message);
2016-11-23 04:57:23 +00:00
this.name = this.constructor.name;
2016-10-21 06:42:17 +00:00
}
}
module.exports = (promise, ms, fallback) => new Promise((resolve, reject) => {
if (typeof ms !== 'number') {
throw new TypeError('Expected `ms` to be a number');
2016-10-21 06:42:17 +00:00
}
const timer = setTimeout(() => {
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);
}, ms);
promise.then(
val => {
clearTimeout(timer);
resolve(val);
},
err => {
clearTimeout(timer);
reject(err);
}
);
});
module.exports.TimeoutError = TimeoutError;