Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 73351f9

Browse files
authored
Merge pull request HackYourFuture#397 from gajduk-mansystems/master
week3 LessonPlan
2 parents 35b32e3 + bb888a0 commit 73351f9

File tree

1 file changed

+171
-42
lines changed

1 file changed

+171
-42
lines changed

Week2/LESSONPLAN.md

Lines changed: 171 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -18,56 +18,149 @@ FIRST HALF (12.00 - 13.30)
1818
- It's a way to introduce asynchronicity to your application
1919
- Makes asynchronous code read like it's synchronous
2020
### 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**
2125
```javascript
22-
let promiseToDoHomeWork = new Promise(function (resolve, reject) {
23-
let isDone = true;
26+
let doHomeWork = function (cb) {
27+
setTimeout(function () {
28+
if ( true )
29+
cb(); // homework done
30+
else
31+
cb('homework not done, too lazy');
32+
}, 1000);
33+
}
2434

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 = new Promise(function (resolve, reject) {
47+
setTimeout(function () {
48+
if ( true )
49+
resolve(); // homework done
50+
else
51+
reject('homework not done, too lazy');
52+
}, 1000);
3053
});
3154

3255
promiseToDoHomeWork
3356
.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+
let attendClass = 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+
let doTheHomeWork = 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+
}
3580

81+
let submitHomeWork = 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+
})
36108
```
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 )`.
38111

39112
```javascript
40113

41114
let attendClass = function () {
42115
return new Promise(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);
44122
});
45123
}
46124

47125
let doTheHomeWork = function (message) {
48126
return new Promise(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);
50133
});
51134
}
52135

53-
let submitHomework = function (message) {
136+
let submitHomeWork = function (message) {
54137
return new Promise(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);;
56144
});
57145
}
58146

59147
attendClass()
60148
.then(function (result) {
61149
return doTheHomeWork(result);
62150
})
63-
.then(function () {
64-
return submitHomework(result);
65-
}).catch(function (error) {
66-
console.log(error);
151+
.then(function (result) {
152+
return submitHomeWork(result);
153+
})
154+
.then(function (result) {
155+
console.log(result);
156+
})
157+
.catch(function (error) {
158+
console.warn(error);
67159
});
68160

69-
```
70161

162+
```
163+
Simulate an error in doTheHomeWork by replacing `if ( true )` with `if ( false )` and run the example again.
71164

72165
- Promise.all
73166

@@ -81,39 +174,75 @@ Promise.all([attendClass(), doTheHomeWork(), submitHomework()]).then(function ([
81174
Promise.race([attendClass(), doTheHomeWork(), submitHomework()]).then(function (result) { console.log('one of them finished') });
82175
```
83176

84-
- Example for converting XHR to promise as a preparation for `fetch`
177+
### Exercise
178+
179+
#### Easy exercise (see difficult exercise alternative below)
180+
181+
**Part 1**
182+
Rewrite the following code to use promise instead of callbacks. *As preparation for `fetch`*
85183

86184
```javascript
87-
function fetchResource(url) {
88-
return new Promise(function (resolve, reject) {
89-
const oReq = new XMLHttpRequest();
90-
oReq.open('GET', url);
91-
oReq.send();
92-
oReq.addEventListener('load', function (event) {
93-
const data = JSON.parse(this.response);
94-
if (data.cod >= 400) {
95-
// error
96-
console.log('error', data);
97-
reject(data);
98-
} else {
99-
//success
100-
console.log('success', data);
101-
resolve(data);
102-
}
103-
});
185+
{
186+
const WEATHER_URL = `https://api.openweathermap.org/data/2.5/weather?q=amsterdam&appid=316f8218c0899311cc029a305f39575e`;
187+
188+
function fetchResourceAsCallback(url, cb) {
189+
const oReq = new XMLHttpRequest();
190+
oReq.open('GET', url);
191+
oReq.send();
192+
oReq.addEventListener('load', function (event) {
193+
const response = JSON.parse(this.response);
194+
if (response.code >= 400) {
195+
// error
196+
cb("Failed to get because:"+response);
197+
} else {
198+
//success
199+
cb(null, response);
200+
}
104201
});
105202
}
106203

107-
fetchResource(`https://api.openweathermap.org/data/2.5/weather?q=amsterdam&appid=316f8218c0899311cc029a305f39575e`).then(function (result) {
204+
fetchResourceAsCallback(WEATHER_URL,
205+
function (err, data) {
206+
if ( err )
207+
console.warn(err);
208+
else
209+
console.log(data);
210+
}
211+
);
212+
213+
function fetchResourceAsPromise(url) {
214+
// your code goes in here
215+
}
216+
217+
fetchResourceAsPromise(WEATHER_URL).then(function (result) {
108218
console.log(result);
219+
})
220+
.catch(function (err) {
221+
console.warn(err);
109222
});
223+
}
110224

111225
```
112226

113-
### Excercise
227+
**Part 2**
228+
229+
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.
230+
231+
```javascript
232+
233+
const URLS_TO_LOAD = [ 'https://samples.openweathermap.org/data/2.5/weather?q=London&appid=316f8218c0899311cc029a305f39575e', 'https://api.openweathermap.org/data/2.5/weather?q=amsterdam&appid=316f8218c0899311cc029a305f39575e'];
234+
```
235+
236+
* 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+
114242
> 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 💍
115243
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:
117246

118247
1. Gathering the ingredients (pasta, garlic, tomatoes, sage, butter)
119248
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
124253
7. Baking the tomatoes
125254
X. Mixing the pasta with sauce
126255

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!
128257

129258
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!)
130259
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
142271
### Essence
143272

144273
- 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
146275

147276
## 2. How to use the `fetch` API to do AJAX calls
148277

@@ -311,7 +440,7 @@ person2Display(); // Prints Name: Paul Adams
311440

312441
The this keyword works differently in arrow functions.
313442

314-
- The `this` value inside the arrow function gets binded and calcuated and assigned based on its wrapper/container/parent `this` value.
443+
- The `this` value inside the arrow function gets binded and calculated and assigned based on its wrapper/container/parent `this` value.
315444
- The methods call(), apply(), and bind() will not change the value of this in arrow functions
316445
### Example
317446
```javascript

0 commit comments

Comments
 (0)