-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path1-count.js
More file actions
59 lines (50 loc) · 1.33 KB
/
1-count.js
File metadata and controls
59 lines (50 loc) · 1.33 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
'use strict';
const DataCollector = function (expected, timeout, callback) {
this.expected = expected;
this.count = 0;
this.data = {};
this.finished = false;
this.doneCallback = callback;
this.timer = setTimeout(() => {
if (this.finished) return;
const err = new Error('Collector timed out');
this.finished = true;
this.doneCallback(err);
}, timeout);
};
DataCollector.prototype.collect = function (key, data) {
if (this.finished) return;
this.count++;
if (data instanceof Error) {
this.finished = true;
this.doneCallback(data);
return;
}
this.data[key] = data;
if (this.expected === this.count) {
if (this.timer) clearTimeout(this.timer);
this.finished = true;
this.doneCallback(null, this.data);
}
};
// Usage
const dc1 = new DataCollector(3, 1000, (err, result) => {
console.log('dc1');
console.dir({ err, result });
});
dc1.collect('key1', 1);
dc1.collect('key2', 2);
dc1.collect('key3', 3);
const dc2 = new DataCollector(3, 1000, (err, result) => {
console.log('dc2');
console.dir({ err, result });
});
dc2.collect('key1', 1);
dc2.collect('key2', 2);
const dc3 = new DataCollector(3, 1000, (err, result) => {
console.log('dc3');
console.dir({ err, result });
});
dc3.collect('key1', new Error('Collect an error'));
dc3.collect('key2', 2);
dc3.collect('key3', 3);