-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy path9-events.js
More file actions
44 lines (32 loc) · 1.07 KB
/
9-events.js
File metadata and controls
44 lines (32 loc) · 1.07 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
'use strict';
const { EventEmitter } = require('node:events');
const ee = new EventEmitter();
// Emulate asynchronous calls
const wrapAsync = (fn) => (...args) => setTimeout(
() => fn(...args), Math.floor(Math.random() * 1000)
);
// Asynchronous functions
const readConfig = wrapAsync((name) => {
console.log('(1) config loaded');
ee.emit('config', { name });
});
const doQuery = wrapAsync((statement) => {
console.log('(2) SQL query executed: ' + statement);
ee.emit('query', [ { name: 'Kiev' }, { name: 'Roma' } ]);
});
const httpGet = wrapAsync((url) => {
console.log('(3) Page retrieved: ' + url);
ee.emit('page', '<html>Some archaic web here</html>');
});
const readFile = wrapAsync((path) => {
console.log('(4) Readme file loaded: ' + path);
ee.emit('done', 'file content');
});
// Example
console.log('start');
readConfig('myConfig');
ee.on('config', doQuery.bind(null, 'select * from cities'));
ee.on('query', httpGet.bind(null, 'http://kpi.ua'));
ee.on('page', readFile.bind(null, 'README.md'));
ee.on('done', () => console.log('done'));
console.log('end');