forked from thalesmello/exploring-async
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path03_callbacks_named.js
54 lines (44 loc) · 1.19 KB
/
03_callbacks_named.js
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
var aBootTime = 1000,
bBootTime = 1000,
queueCallback = null,
serverHandler = null;
serverA();
serverB();
function serverA() {
console.log("A: Booting up system...");
setTimeout(checkNetwork, aBootTime);
function checkNetwork() {
console.log("A: Checking network connection");
setTimeout(sendRequest, 500);
}
function sendRequest() {
console.log("A: Request complex computation");
sendNetworkRequest(callback);
}
function callback(value) {
console.log("A: Computation returned " + value);
}
}
function serverB() {
console.log("B: Booting up system...")
setTimeout(listenRequests, bBootTime);
function listenRequests() {
console.log("B: Server up and running");
serverHandler = handler;
if (queueCallback) {
serverHandler(queueCallback);
queueCallback = null;
}
}
function handler(callback) {
console.log("B: Starting heavy computation");
setTimeout(() => callback(42), 2000)
}
}
function sendNetworkRequest(callback) {
if(serverHandler) {
serverHandler(callback);
} else {
queueCallback = callback;
}
}