-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathasync-event-emitter.js
46 lines (41 loc) · 1.05 KB
/
async-event-emitter.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
const EventEmitter = require("events");
const fs = require("fs");
const promisify = require("./promisify");
class WithTime extends EventEmitter {
async execute(asyncFunc, ...args) {
this.emit("begin");
try {
console.time("execute");
const data = await asyncFunc(...args);
this.emit("data", data);
console.timeEnd("execute");
this.emit("end");
} catch (err) {
this.emit("error", err);
}
}
}
const readFileAsArray = async file => {
try {
const readFile = promisify(fs.readFile);
const data = await readFile([file]);
const lines = data
.toString()
.trim()
.split("\n");
return lines;
} catch (error) {
throw new Error(error);
}
};
const withTime = new WithTime();
withTime.on("begin", () => console.log("About to execute"));
withTime.on("end", () => console.log("Done with execute"));
withTime.on("data", data => {
console.log(data);
});
withTime.on("error", error => {
console.log(error);
});
const filename = "test.txt";
withTime.execute(readFileAsArray, filename);