-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcallback_promise_async.js
More file actions
43 lines (39 loc) · 943 Bytes
/
callback_promise_async.js
File metadata and controls
43 lines (39 loc) · 943 Bytes
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
// Callback Hell
getData("/users/1", function (err, user) {
if (err) {
return;
}
getData(`${user.id}/posts`, function (err, posts) {
if (err) {
return;
}
getData(`${posts[0].id}/comments`, function (err, comments) {
if (err) {
return;
}
console.log(comments[0].body);
});
});
});
// Promises
getData("/users/1")
.then(user => {
return getData(`users/${user.id}/posts`);
})
.then(posts => {
return getData(`/${posts[0].id}/comments`);
})
.then(comments => {
console.log(comments[0].body);
})
.catch(err => console.error("Something went wrong:", err));
// Async await
try {
const user = await getData("/users/1");
const posts = await getData(`/users/${user.id}/posts`);
const comments = await getData(`/${posts[0].id}/comments`);
console.log(comments[0].body);
} catch (error) {
console.error("Something went wrong:", error);
}
}