-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path6-for.js
More file actions
56 lines (45 loc) · 1.23 KB
/
6-for.js
File metadata and controls
56 lines (45 loc) · 1.23 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
'use strict';
class Proactor {
#tasks = [];
enqueue(fn, callback) {
this.#tasks.push({ fn, callback });
}
start() {
if (!this.#tasks.length) return;
const tasks = this.#tasks.splice(0);
this.#phase(tasks);
}
#phase(tasks) {
let counter = tasks.legth;
for (const task of tasks) {
task.fn((err, data) => {
task.callback(err, data);
if (--counter === 0) this.start();
});
}
}
}
// Usage
const eventLoop = new Proactor();
const fakeAsyncRead = (name, callback) => {
const delay = Math.random() * 1000;
const fn = (done) => {
setTimeout(() => {
done(null, 'FILE DATA');
}, delay);
};
eventLoop.enqueue(fn, callback);
};
fakeAsyncRead('File A', (err, data) => {
if (err) console.error(`[Proactor] File A: failed "${err.message}"`);
else console.log(`[Proactor] File A: done "${data}"`);
});
fakeAsyncRead('File B', (err, data) => {
if (err) console.error(`[Proactor] File B: failed "${err.message}"`);
else console.log(`[Proactor] File B: done "${data}"`);
});
fakeAsyncRead('File C', (err, data) => {
if (err) console.error(`[Proactor] File C: failed "${err.message}"`);
else console.log(`[Proactor] File C: done "${data}"`);
});
eventLoop.start();