File tree
Expand file treeCollapse file tree1 file changed
+53
-0
lines changed Expand file treeCollapse file tree1 file changed
+53
-0
lines changed Original file line number | Diff line number | Diff line change |
---|
|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +// Emulate Asynchronous calls |
| 4 | + |
| 5 | +const wrapAsync = () => new Promise((resolve, reject) => |
| 6 | +setTimeout(resolve, Math.floor((Math.random() * 1000))) |
| 7 | +); |
| 8 | + |
| 9 | +// Asynchronous functions |
| 10 | + |
| 11 | +const readConfig = async (name) => { |
| 12 | +await wrapAsync(); |
| 13 | +console.log('(1) config loaded'); |
| 14 | +return { name }; |
| 15 | +} |
| 16 | + |
| 17 | +const doQuery = async (statement) => { |
| 18 | +await wrapAsync(); |
| 19 | +console.log('(2) SQL query executed: ' + statement); |
| 20 | +return [{ name: 'Kiev' }, { name: 'Roma' }]; |
| 21 | +}; |
| 22 | + |
| 23 | +const httpGet = async (url) => { |
| 24 | +await wrapAsync(); |
| 25 | +console.log('(3) Page retrieved: ' + url); |
| 26 | +return '<html>Some archaic web here</html>'; |
| 27 | +}; |
| 28 | + |
| 29 | +const readFile = async (path) => { |
| 30 | +await wrapAsync(); |
| 31 | +console.log('(4) Readme file loaded: ' + path); |
| 32 | +return 'file content'; |
| 33 | +}; |
| 34 | + |
| 35 | +// Usage |
| 36 | + |
| 37 | +(async () => { |
| 38 | +const config = await readConfig('myConfig'); |
| 39 | +const res = await doQuery('select * from cities'); |
| 40 | +let json, file; |
| 41 | +try { |
| 42 | +json = await httpGet('http://kpi.ua'); |
| 43 | +} catch (err) { |
| 44 | +console.log('Error (1): ' + err.message); |
| 45 | +} |
| 46 | +try { |
| 47 | +file = await readFile('README.md'); |
| 48 | +} catch (err) { |
| 49 | +console.log('Reject reason (2): ' + err.message); |
| 50 | +} |
| 51 | +console.log('Done'); |
| 52 | +console.dir({ config, res, json, file }); |
| 53 | +})(); |
You can’t perform that action at this time.
0 commit comments