|
1 | 1 | 'use strict'; |
2 | 2 |
|
3 | | -function chain(prev = null) { |
| 3 | +const chain = (prev = null) => { |
4 | 4 | console.log('Create element'); |
5 | 5 | const cur = () => { |
6 | 6 | console.log('Reverse from ' + (cur.fn ? cur.fn.name : 'null')); |
@@ -29,50 +29,42 @@ function chain(prev = null) { |
29 | 29 | }); |
30 | 30 | }; |
31 | 31 | return cur; |
32 | | -} |
| 32 | +}; |
33 | 33 |
|
34 | | -// Emulate Asynchronous calls |
| 34 | +// Emulate asynchronous calls |
35 | 35 |
|
36 | | -function wrapAsync(callback) { |
37 | | - setTimeout(callback, Math.floor((Math.random() * 1000))); |
38 | | -} |
| 36 | +const wrapAsync = fn => (...args) => setTimeout( |
| 37 | + () => fn(...args), Math.floor((Math.random() * 1000)) |
| 38 | +); |
39 | 39 |
|
40 | 40 | // Asynchronous functions |
41 | 41 |
|
42 | | -function readConfig(name, callback) { |
43 | | - wrapAsync(() => { |
44 | | - console.log('(1) config loaded'); |
45 | | - callback(null, { name }); |
46 | | - }); |
47 | | -} |
| 42 | +const readConfig = wrapAsync((name, callback) => { |
| 43 | + console.log('(1) config loaded'); |
| 44 | + callback(null, { name }); |
| 45 | +}); |
48 | 46 |
|
49 | | -function selectFromDb(query, callback) { |
50 | | - wrapAsync(() => { |
51 | | - console.log('(2) SQL query executed'); |
52 | | - callback(null, [ { name: 'Kiev' }, { name: 'Roma' } ]); |
53 | | - }); |
54 | | -} |
| 47 | +const selectFromDb = wrapAsync((query, callback) => { |
| 48 | + console.log('(2) SQL query executed'); |
| 49 | + callback(null, [{ name: 'Kiev' }, { name: 'Roma' } ]); |
| 50 | +}); |
55 | 51 |
|
56 | | -function getHttpPage(url, callback) { |
57 | | - wrapAsync(() => { |
58 | | - console.log('(3) Page retrieved'); |
59 | | - callback(null, '<html>Some archaic web here</html>'); |
60 | | - }); |
61 | | -} |
| 52 | +const getHttpPage = wrapAsync((url, callback) => { |
| 53 | + console.log('(3) Page retrieved'); |
| 54 | + callback(null, '<html>Some archaic web here</html>'); |
| 55 | +}); |
62 | 56 |
|
63 | | -function readFile(path, callback) { |
64 | | - wrapAsync(() => { |
65 | | - console.log('(4) Readme file loaded'); |
66 | | - callback(null, 'file content'); |
67 | | - }); |
68 | | -} |
| 57 | +const readFile = wrapAsync((path, callback) => { |
| 58 | + console.log('(4) Readme file loaded'); |
| 59 | + callback(null, 'file content'); |
| 60 | +}); |
69 | 61 |
|
70 | 62 | // Usage |
71 | 63 |
|
72 | | -const c1 = chain() |
| 64 | +const startChain = chain() |
73 | 65 | .do(readConfig, 'myConfig') |
74 | 66 | .do(selectFromDb, 'select * from cities') |
75 | 67 | .do(getHttpPage, 'http://kpi.ua') |
76 | 68 | .do(readFile, 'README.md'); |
77 | 69 |
|
78 | | -c1(); |
| 70 | +startChain(); |
0 commit comments