Skip to content

Commit c508820

Browse files
committed
Add examples
1 parent c4d7228 commit c508820

2 files changed

Lines changed: 67 additions & 0 deletions

File tree

‎JavaScript/1-reactor.js‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
'use strict';
2+
3+
class Reactor {
4+
#tasks = [];
5+
6+
enqueue(fn) {
7+
this.#tasks.push(fn);
8+
}
9+
10+
start() {
11+
while (this.#tasks.length) {
12+
const tasks = this.#tasks.splice(0);
13+
for (const fn of tasks) fn();
14+
}
15+
}
16+
}
17+
18+
// Usage
19+
20+
const eventLoop = new Reactor();
21+
22+
const fakeAsyncRead = (name) => () => {
23+
const timeout = Math.random() * 1000;
24+
setTimeout(() => {
25+
console.log(`[Reactor] ${name} done`);
26+
}, timeout);
27+
};
28+
29+
eventLoop.enqueue(fakeAsyncRead('File A'));
30+
eventLoop.enqueue(fakeAsyncRead('File B'));
31+
eventLoop.enqueue(fakeAsyncRead('File C'));
32+
33+
eventLoop.start();

‎JavaScript/2-proactor.js‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
'use strict';
2+
3+
class Proactor {
4+
#tasks = [];
5+
6+
enqueue(fn) {
7+
this.#tasks.push(fn);
8+
}
9+
10+
async start() {
11+
while (this.#tasks.length) {
12+
const tasks = this.#tasks.splice(0);
13+
for (const fn of tasks) await fn();
14+
}
15+
}
16+
}
17+
18+
// Usage
19+
20+
const eventLoop = new Proactor();
21+
22+
const fakeAsyncRead = (name) => async () => {
23+
const delay = Math.random() * 1000;
24+
await new Promise((resolve) => {
25+
setTimeout(resolve, delay);
26+
});
27+
console.log(`[Proactor] ${name} done after ${delay}ms`);
28+
};
29+
30+
eventLoop.enqueue(fakeAsyncRead('File A'));
31+
eventLoop.enqueue(fakeAsyncRead('File B'));
32+
eventLoop.enqueue(fakeAsyncRead('File C'));
33+
34+
eventLoop.start();

0 commit comments

Comments
 (0)