-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtimeout.js
More file actions
66 lines (59 loc) · 2.09 KB
/
timeout.js
File metadata and controls
66 lines (59 loc) · 2.09 KB
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
63
64
65
66
const timing = require('./timing');
function Timeout() {
this.calls = new Set();
this.interval = false;
}
Timeout.prototype.clean = function timeoutClean() {
const now = timing.now();
Array.from(this.calls).forEach(end => end.checkTimeout(now));
};
Timeout.prototype.startWait = function timeoutStartWait(onTimeout, timeout, createTimeoutError, set) {
this.interval = this.interval || setInterval(this.clean.bind(this), 500);
const end = error => {
this.endWait(end, set);
error && onTimeout(error);
};
end.checkTimeout = time => timing.isAfter(time, timeout) && end(createTimeoutError());
this.calls.add(end);
set && set.add(end);
return end;
};
Timeout.prototype.endWait = function timeoutEndWait(end, set) {
this.calls.delete(end);
set && set.delete(end);
if (this.calls.size <= 0 && this.interval) {
clearInterval(this.interval);
this.interval = false;
}
};
Timeout.prototype.startPromise = function timeoutStartPromise(params, fn, $meta, error, set) {
if (Array.isArray($meta && $meta.timeout)) {
return new Promise((resolve, reject) => {
const endWait = this.startWait(waitError => {
$meta.mtid = 'error';
if ($meta.dispatch) {
$meta.dispatch(waitError, $meta);
resolve(false);
} else {
resolve([waitError, $meta]);
}
}, $meta.timeout, error, set);
Promise.resolve(params).then(fn)
.then(result => {
endWait();
resolve(result);
return result;
})
.catch(fnError => {
endWait();
reject(fnError);
});
});
} else {
return Promise.resolve(params).then(fn);
}
};
Timeout.prototype.startRequest = function startRequest($meta, error, onTimeout) {
return Array.isArray($meta && $meta.timeout) && this.startWait(onTimeout, $meta.timeout, error);
};
module.exports = new Timeout();