-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpromises_lecture.html
102 lines (82 loc) · 2.43 KB
/
promises_lecture.html
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
94
95
96
97
98
99
100
101
102
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Promises</title>
</head>
<body>
<script>
function practiceCoding () {
setTimeout(
() => console.log("I'm practicing writing code..."),
2000
);
// this doesn't have an argument so you can specify it in a callback later - it's much more flexible
next();
}
function practiceShortcuts() {
setTimeout(console.log("I'm practicing the refactoring shortcuts"),
3000
);
next();
}
function readNextLesson() {
setTimeout(console.log("I'm reading the next lesson"),
150
);
next();
}
practiceCoding();
practiceShortcuts();
readNextLesson();
console.log("yay, I completed them all!");
// synchronize functions so there is an order: practiceCoding, then practiceShortcuts, then readNextLesson - you use callbacks
// synchronizing using callbacks... must wrap in another function
// BEFORE PROMISES: CALLBACKS (callback hell!)
practiceCoding(
() => practiceShortcuts(
readNextLesson(
() => console.log("I did everything"))
)
);
// represent practiceCoding as a PROMISE, not an action
// resolve: success
// reject: failure
// "if" - I might or might not practice coding (promise always has two states)
let ifPracticedCoding = new Promise(function(resolve, reject) {
practiceCoding();
resolve();
});
let ifPracticeShortcuts = new Promise(function (resolve) {
practiceShortcuts();
resolve();
});
let ifReadNextLesson = new Promise(function (resolve) {
readNextLesson();
resolve();
});
ifPracticedCoding
.then(function () {
return ifPracticeShortcuts;
})
.then(function(){
return ifReadNextLesson;
})
.then(function() {
console.log("yay, I completed all!")
});
resolve();
// arrow syntax
ifPracticedCoding
.then(() => ifPracticeShortcuts)
.then(() => ifReadNextLesson)
.then(() => console.log("yay, I completed all!"));
// alternative way to write the above block of code
Promise.all([
ifPracticedCoding,
ifPracticeShortcuts,
ifReadNextLesson
]).then(() => console.log("yay, I completed all!"))
</script>
</body>
</html>