-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy path2-emulate-async-calls.js
More file actions
53 lines (40 loc) · 1.23 KB
/
Copy path2-emulate-async-calls.js
File metadata and controls
53 lines (40 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
'use strict';
// Run and see random order
// Use global counter to detect finish (bad practice)
const callbackCounter = (count, callback) => {
let counter = 0;
const done = () => {
if (++counter === count) callback();
};
return done;
};
// Emulate asynchronous calls
const wrapAsync = (fn) => (...args) => setTimeout(
() => fn(...args), Math.floor(Math.random() * 1000)
);
// Asynchronous functions
const readConfig = wrapAsync((name, callback) => {
console.log('(1) config loaded');
callback(null, { name });
});
const doQuery = wrapAsync((statement, callback) => {
console.log(`(2) SQL query executed: ${statement}`);
callback(null, [{ name: 'Kiev' }, { name: 'Roma' }]);
});
const httpGet = wrapAsync((url, callback) => {
console.log(`(3) Page retrieved: ${url}`);
callback(null, '<html>Some archaic web here</html>');
});
const readFile = wrapAsync((path, callback) => {
console.log('(4) Readme file loaded');
callback(null, 'file content');
});
console.log('start');
const callback = callbackCounter(4, () => {
console.log('All done!');
});
readConfig('myConfig', callback);
doQuery('select * from cities', callback);
httpGet('http://kpi.ua', callback);
readFile('README.md', callback);
console.log('end');

