-
Notifications
You must be signed in to change notification settings - Fork 5
/
5_pitfalls.js
47 lines (40 loc) · 1.09 KB
/
5_pitfalls.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
const fetch = require("node-fetch");
const url = "https://jsonplaceholder.typicode.com/posts/1";
function isStatus200(res) {
console.log('Checking HTTP response status...');
if (res.status === 200) {
return res
} else {
let err = new Error(res.statusText);
err.response = res;
throw err;
}
}
function getPostJson(res) {
console.log('Getting JSON...');
return res.json()
}
function getTitle(post) {
console.log('Getting Title...');
return post.title
}
function echoTitle(title) {
console.log(title)
}
// Bad news - not returning, nesting, and not catching
// fetch(url).then(isStatus200)
// .then(result => {
// console.log('Got a result...');
// getPostJson(result)
// .then(post => getTitle(post));
// }).then(title => echoTitle(title));
// Better news - terminate chain with catch, flatten
fetch(url)
.then(isStatus200)
.then(result => {
console.log('Got a result...');
return getPostJson(result)
})
.then(getTitle)
.then(echoTitle)
.catch(err => console.error(err));