Refactoring

This commit is contained in:
Alvaro 2017-06-27 15:41:26 +01:00
parent 7bb7ff2be0
commit 4b8acf8cc2
1 changed files with 4 additions and 14 deletions

View File

@ -1,4 +1,5 @@
'use strict'; 'use strict';
const delay = require('delay');
class TimeoutError extends Error { class TimeoutError extends Error {
constructor(message) { constructor(message) {
@ -12,7 +13,7 @@ module.exports = (promise, ms, fallback) => new Promise((resolve, reject) => {
throw new TypeError('Expected `ms` to be a positive number'); throw new TypeError('Expected `ms` to be a positive number');
} }
const timer = setTimeout(() => { delay(ms).then(() => {
if (typeof fallback === 'function') { if (typeof fallback === 'function') {
resolve(fallback()); resolve(fallback());
return; return;
@ -22,18 +23,7 @@ module.exports = (promise, ms, fallback) => new Promise((resolve, reject) => {
const err = fallback instanceof Error ? fallback : new TimeoutError(message); const err = fallback instanceof Error ? fallback : new TimeoutError(message);
reject(err); reject(err);
}, ms);
promise.then(
val => {
clearTimeout(timer);
resolve(val);
},
err => {
clearTimeout(timer);
reject(err);
}
);
}); });
promise.then(resolve, reject);
});
module.exports.TimeoutError = TimeoutError; module.exports.TimeoutError = TimeoutError;