-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy path4-producer-consumer.js
More file actions
47 lines (40 loc) · 743 Bytes
/
4-producer-consumer.js
File metadata and controls
47 lines (40 loc) · 743 Bytes
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
'use strict';
function* sleep(interval) {
const start = new Date();
while (new Date() - start < interval) {
yield;
}
}
function* produce() {
yield* sleep(500);
return Math.random();
}
function* consume() {
let count = 0;
let sum = 0;
while (true) {
const data = yield* produce();
count++;
sum += data;
console.log(
`Got data: ${data}\n` +
`Count: ${count}\n` +
`Sum: ${sum}\n` +
`Average: ${sum / count}\n`,
);
}
}
function* anotherTask() {
while (true) {
yield* sleep(1000);
console.log('Hello!\n');
}
}
const consumer = consume();
const task = anotherTask();
const step = () => {
consumer.next();
task.next();
setImmediate(step);
};
step();