forked from HowProgrammingWorks/AsynchronousProgramming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathg-async-await.js
More file actions
53 lines (44 loc) · 1.16 KB
/
Copy pathg-async-await.js
File metadata and controls
53 lines (44 loc) · 1.16 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';
// Emulate Asynchronous calls
const pause = () => new Promise((resolve) =>
setTimeout(resolve, Math.floor(Math.random() * 1000))
);
// Asynchronous functions
const readConfig = async (name) => {
await pause();
console.log('(1) config loaded');
return { name };
};
const doQuery = async (statement) => {
await pause();
console.log('(2) SQL query executed: ' + statement);
return [{ name: 'Kiev' }, { name: 'Roma' }];
};
const httpGet = async (url) => {
await pause();
console.log('(3) Page retrieved: ' + url);
return '<html>Some archaic web here</html>';
};
const readFile = async (path) => {
await pause();
console.log('(4) Readme file loaded: ' + path);
return 'file content';
};
// Usage
(async () => {
const config = await readConfig('myConfig');
const res = await doQuery('select * from cities');
let json, file;
try {
json = await httpGet('http://kpi.ua');
} catch (err) {
console.log('Error (1): ' + err.message);
}
try {
file = await readFile('README.md');
} catch (err) {
console.log('Reject reason (2): ' + err.message);
}
console.log('Done');
console.dir({ config, res, json, file });
})();