-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpractice.js
More file actions
93 lines (73 loc) · 2.36 KB
/
Copy pathpractice.js
File metadata and controls
93 lines (73 loc) · 2.36 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// Callback Functions
function connectToDatabase(queryFunction, query) {
let randomTime = Math.floor(Math.random() * 2000) + 1;
setTimeout(() => {
console.log('Connection Established');
queryFunction(query);
}, randomTime);
}
function queryData(query) {
let randomTime = Math.floor(Math.random() * 1000) + 1;
setTimeout(() => {
console.log(query);
}, randomTime);
}
connectToDatabase(queryData, 'select * from Employees');
// ////////////////////////////////////////
// Promises
// output "A" after a random time between 0 & 3 seconds
function outputA() {
let randomTime = Math.floor(Math.random() * 3000) + 1;
return new Promise((resolve, reject) => {
setTimeout(() => {
randomTime % 2 ? resolve('A') : reject('Error with outputA()');
}, randomTime);
});
}
// output "B" after a random time between 0 & 3 seconds
function outputB() {
let randomTime = Math.floor(Math.random() * 3000) + 1;
return new Promise((resolve, reject) => {
setTimeout(() => {
randomTime % 2 ? resolve('B') : reject('Error with outputB()');
}, randomTime);
});
}
// output "C" after a random time between 0 & 3 seconds
function outputC() {
let randomTime = Math.floor(Math.random() * 3000) + 1;
return new Promise((resolve, reject) => {
setTimeout(() => {
randomTime % 2 ? resolve('C') : reject('Error with outputC()');
}, randomTime);
});
}
// outputA()
// .then((data) => {
// console.log(data); // output the result of "outputA()" to the console
// return outputB();
// })
// .then((data) => {
// console.log(data); // output the result of "outputB()" to the console
// return outputC();
// })
// .then((data) => {
// console.log(data); // output the result of "outputC()" to the console
// })
// .catch((err) => {
// console.log(err); // output the error to the console
// });
async function showOutput() {
try {
let A = await outputA();
console.log(A); // output the result of "outputA()" to the console
let B = await outputB();
console.log(B); // output the result of "outputB()" to the console
let C = await outputC();
console.log(C); // output the result of "outputC()" to the console
} catch (err) {
console.log(err); // output the error for outputA(), outputB() or outputC() to the console
}
}
showOutput();
// ////////////////////////////////////////