-
Notifications
You must be signed in to change notification settings - Fork 0
/
promise.js
63 lines (60 loc) · 1.14 KB
/
promise.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
63
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"
}
];
// any promises had this methods .then .catch .finally
function getBookById(id) {
return new Promise((resolve, reject) => {
const book = booksDB.find(book => book.id === id);
if(!book) {
const error = new Error();
error.message = "Book not found";
reject(error);
}
resolve(book);
});
}
function getAuthorById(id){
return new Promise((resolve, reject) => {
const author = authorsDB.find(author => author.id === id);
if(!author) {
const error = new Error();
error.message = "Author not found";
reject(error);
}
resolve(author);
})
}
getBookById(1)
.then(book => {
return getAuthorById(book.authorId)
})
.then(author => {
console.log(`the book was written by ${author.name}`);
})
.catch(err => {
console.error(err.message);
})