-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
62 lines (54 loc) · 1.39 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
'use strict';
const isFunction = (obj) => (typeof obj === 'function');
const timeout = function () {
return new Promise((resolve, reject) => {
// user input is one of:
// - timeout(mil, promise)
// - timeout(mil, handler, promise)
const mil = arguments[0];
const handler = arguments.length === 3 ? arguments[1] : undefined;
const promise = arguments.length === 3 ? arguments[2] : arguments[1];
// start the timer
const delay = new Promise(r => setTimeout(r, mil));
let finished = false;
promise
.then(result => {
if (finished) return;
finished = true;
resolve(result);
})
.catch(error => {
if (finished) return;
finished = true;
reject(error);
});
delay
.then(result => {
if (finished) return;
finished = true;
let error = new Error('TIMEOUT');
if (handler && isFunction(handler.emit)) handler.emit('error', error);
reject(error);
});
});
};
const timeify = function (func) {
return function () {
const mil = arguments[0];
const funcArguments = Array.apply(null, arguments).slice(1);
let promise = func.apply(this, funcArguments);
return timeout(mil, this, promise);
};
};
const timeifyAll = function (obj) {
for (let name in obj) {
if (!obj.hasOwnProperty(name) || !isFunction(obj[name])) continue;
obj[`${name}Timeout`] = timeify(obj[name]);
}
return obj;
};
module.exports = {
timeout,
timeify,
timeifyAll
};