-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcallback.js
62 lines (57 loc) · 1.15 KB
/
callback.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
const booksDB = [
{
id: 1,
title: "Clean Code",
authorId: 1
},
{
id: 2,
title: "The pragmatic programmer",
authorId: 2
},
{
id: 3,
title: "Web development with Node.js",
authorId: 3
}
];
const authorsDB = [
{
id: 1,
name: "Some guy"
},
{
id: 2,
name: "Pinoccio"
}
];
function getBookById(id, callback) {
const book = booksDB.find(book => book.id === id);
if(!book) {
const error = new Error();
error.message = "Book not found";
return callback(error);
}
callback(null, book);
}
function getAuthorById(id, callback){
const author = authorsDB.find(author => author.id === id);
if(!author) {
const error = new Error();
error.message = "Author not found";
return callback(error);
}
callback(null, author);
}
getBookById(2, (err, book) => {
if(err) {
return console.log(err.message);
}
getAuthorById(book.authorId, (err, author) => { // callback hell means to have too many nested functions
if(err) {
return console.log(err.message);
}
console.log(`this book ${book.title} was writen by ${author.name}`)
})
return console.log(book);
});