You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
- It's a way to introduce asynchronicity to your application
19
19
- Makes asynchronous code read like it's synchronous
20
20
### Example
21
+
22
+
In the examples `setTimeout` is used to illustrate asynchronous code. In the real world there will be some code doing useful work here, for example `fetch`.
23
+
24
+
**Callback**
21
25
```javascript
22
-
let promiseToDoHomeWork =newPromise(function (resolve, reject) {
23
-
let isDone =true;
26
+
letdoHomeWork=function (cb) {
27
+
setTimeout(function () {
28
+
if ( true )
29
+
cb(); // homework done
30
+
else
31
+
cb('homework not done, too lazy');
32
+
}, 1000);
33
+
}
24
34
25
-
if (isDone) {
26
-
resolve('homework is done!');
27
-
} else {
28
-
reject('not done!');
29
-
}
35
+
36
+
doHomeWork(function (err) {
37
+
if ( err )
38
+
console.warn(err);
39
+
else
40
+
console.log('home work is done now');
41
+
})
42
+
```
43
+
44
+
**Promise**
45
+
```javascript
46
+
let promiseToDoHomeWork =newPromise(function (resolve, reject) {
47
+
setTimeout(function () {
48
+
if ( true )
49
+
resolve(); // homework done
50
+
else
51
+
reject('homework not done, too lazy');
52
+
}, 1000);
30
53
});
31
54
32
55
promiseToDoHomeWork
33
56
.then(function () { console.log('home work is done now'); })
34
-
.catch(function () { console.log('home work has something wrong, can\'t be done'); })
57
+
.catch(function (err) { console.warn(err); })
58
+
59
+
```
60
+
#### Nested callback/promises example
61
+
62
+
```javascript
63
+
letattendClass=function (cb) {
64
+
setTimeout(function () {
65
+
if ( true )
66
+
cb(null, 'I attend the class');
67
+
else
68
+
cb('class not attended, stayed home');
69
+
}, 1000);
70
+
}
71
+
72
+
letdoTheHomeWork=function (message, cb) {
73
+
setTimeout(function () {
74
+
if ( true )
75
+
cb(null, message +' then I did the homework');
76
+
else
77
+
cb('homework not done, was lazy');
78
+
}, 1000);
79
+
}
35
80
81
+
letsubmitHomeWork=function (message, cb) {
82
+
setTimeout(function () {
83
+
if ( true )
84
+
cb(null, message +' so I submit my homework');
85
+
else
86
+
cb('homework not submited, github is down');
87
+
}, 1000);
88
+
}
89
+
90
+
// call attendClass, after it is finished call doTheHomeWork then submitHomeWork. In each step pass the output of the previous step. In case of an error show it in the console
91
+
92
+
attendClass(function (err, data) {
93
+
if ( err )
94
+
console.warn(err);
95
+
else
96
+
doTheHomeWork(data, function (err1, data1) {
97
+
if ( err1 )
98
+
console.warn(err1);
99
+
else
100
+
submitHomeWork(data1, function (err2, data2) {
101
+
if ( err2 )
102
+
console.warn(err2);
103
+
else
104
+
console.log(data2)
105
+
});
106
+
})
107
+
})
36
108
```
37
-
- Nested promises example
109
+
Mention how this nested structure is hard to understand and read. Multiple variables with similar names and error handling is all over the place.
110
+
Simulate an error in doTheHomeWork by replacing `if ( true )` with `if ( false )`.
38
111
39
112
```javascript
40
113
41
114
letattendClass=function () {
42
115
returnnewPromise(function (resolve, reject) {
43
-
resolve('I attend the class');
116
+
setTimeout(function () {
117
+
if ( true )
118
+
resolve('I attend the class');
119
+
else
120
+
reject('class not attended, stayed home');
121
+
}, 1000);
44
122
});
45
123
}
46
124
47
125
letdoTheHomeWork=function (message) {
48
126
returnnewPromise(function (resolve, reject) {
49
-
resolve(message +'then I did the homework');
127
+
setTimeout(function () {
128
+
if ( true )
129
+
resolve(message +' then I did the homework');
130
+
else
131
+
reject('homework not done, was lazy');
132
+
}, 1000);
50
133
});
51
134
}
52
135
53
-
letsubmitHomework=function (message) {
136
+
letsubmitHomeWork=function (message) {
54
137
returnnewPromise(function (resolve, reject) {
55
-
resolve(message +'so I submit my homework');
138
+
setTimeout(function () {
139
+
if ( true )
140
+
resolve(message +' so I submit my homework');
141
+
else
142
+
reject('homework not submited, github is down');
143
+
}, 1000);;
56
144
});
57
145
}
58
146
59
147
attendClass()
60
148
.then(function (result) {
61
149
returndoTheHomeWork(result);
62
150
})
63
-
.then(function () {
64
-
returnsubmitHomework(result);
65
-
}).catch(function (error) {
66
-
console.log(error);
151
+
.then(function (result) {
152
+
returnsubmitHomeWork(result);
153
+
})
154
+
.then(function (result) {
155
+
console.log(result);
156
+
})
157
+
.catch(function (error) {
158
+
console.warn(error);
67
159
});
68
160
69
-
```
70
161
162
+
```
163
+
Simulate an error in doTheHomeWork by replacing `if ( true )` with `if ( false )` and run the example again.
Use `Promise.all` to load data for multiple cities in parallel. Ask students to discuss in which scenarios it would be better to load data in parallel. In what scenarios is loading data in parallel not better.
* Hint: use `map` to convert from an array of URLs to an array of promises.
237
+
238
+
**Alternative exercise - Cooking pasta**
239
+
240
+
**❗❗❗ Difficult exercise ❗❗❗**
241
+
114
242
> Async can be hard to understand without real live example. Cooking is a great example of mixed synchronous and asynchronous tasks. In this assignment we'll cook pasta with promises 💍
115
243
116
-
Let's say we want a programme to cook some pasta. Some of the steps involved in cooking pasta are:
244
+
245
+
Let's say we want a program to cook some pasta. Some of the steps involved in cooking pasta are:
117
246
118
247
1. Gathering the ingredients (pasta, garlic, tomatoes, sage, butter)
119
248
2. Cutting the garlic
@@ -124,7 +253,7 @@ Let's say we want a programme to cook some pasta. Some of the steps involved in
124
253
7. Baking the tomatoes
125
254
X. Mixing the pasta with sauce
126
255
127
-
If we do this synchronolously there is no chance of it becoming a good meal because the pasta would be cold by the time the vegetables are ready. It would also take way too long this way. So let's fix that!
256
+
If we do this synchronously there is no chance of it becoming a good meal because the pasta would be cold by the time the vegetables are ready. It would also take way too long this way. So let's fix that!
128
257
129
258
1. Think about how to do this asynchronously; which tasks could be run at the same time? What steps should wait for what other steps? Try to write down a basic recipe (don't write any code yet!)
130
259
2. Now convert your recipe to pseudocode (in markdown). The point is to name functions and show which functions call which other functions. The logic should be there but we'll write the code in the next step.
@@ -142,7 +271,7 @@ If we do this synchronolously there is no chance of it becoming a good meal beca
142
271
### Essence
143
272
144
273
- It's the accepted solution to [callback hell](http://callbackhell.com/)
145
-
274
+
- in terms of features it does not offer something new, everything one can do with promises could also be done with callbacks but it is easier to write and read the code when promises are used
146
275
147
276
## 2. How to use the `fetch` API to do AJAX calls
148
277
@@ -170,7 +299,7 @@ SECOND HALF (14.00 - 16.00)
170
299
## 3. The `this` keyword and its relationship with `scope`
171
300
172
301
### Explanation
173
-
- The environment(or scope) in which the line is being executed is know as “Execution Context”
302
+
- The environment(or scopeis knownich the line is being executed is know as “Execution Context”
174
303
- The object that `this` refers to, changes every time execution context is changed.
175
304
- Whatever is calling the function passes the `this` value to it by default.
176
305
- We can pass specific `this` by `.bind`, `.call` or `.apply`
0 commit comments