-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasync-await.js
62 lines (56 loc) · 1.01 KB
/
async-await.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"
}
];
async function getBookById(id) {
const book = booksDB.find(book => book.id === id);
if(!book) {
const error = new Error();
error.message = "Book not found";
throw error;
}
return book;
}
async function getAuthorById(id) {
const author = authorsDB.find(author => author.id === id);
if(!author) {
const error = new Error();
error.message = "Author not found";
throw error;
}
return author;
}
async function main() {
try {
const book = await getBookById(1);
const author = await getAuthorById(book.authorId);
console.log(`book ${book.title} written by ${author.name}`);
}
catch (err) {
console.log(err.message);
}
}
main();