-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path4-await.js
More file actions
57 lines (46 loc) · 1.1 KB
/
4-await.js
File metadata and controls
57 lines (46 loc) · 1.1 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
'use strict';
const timers = require('node:timers/promises');
class Proactor {
#tasks = [];
#active = false;
enqueue(fn) {
this.#tasks.push(fn);
}
async start() {
this.#active = true;
while (this.#active) {
const tasks = this.#tasks.splice(0);
for (const fn of tasks) await fn();
await timers.setTimeout(100);
}
}
stop() {
this.#tasks.splice(0);
this.#active = false;
}
}
// Usage
const eventLoop = new Proactor();
const fs = require('node:fs/promises');
const readAsync = (name, encoding = 'utf8') => {
const promise = new Promise((resolve, reject) => {
eventLoop.enqueue(async () => {
try {
const data = await fs.readFile(name, encoding);
console.log(`[Proactor] Read file: ${name}`);
resolve(data);
} catch (err) {
console.error(`[Proactor] Failed to read file: ${name}`, err);
reject(err);
}
});
});
return promise;
};
const main = async () => {
eventLoop.start();
const data = await readAsync('./4-await.js');
console.log('File content:', data);
eventLoop.stop();
};
main();