-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasync-await.js
66 lines (57 loc) · 1.58 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
63
64
65
66
// Javascript Nuggets
// async / await
// async must be present, always returns a promise
// await waits till promise is settled
// error handling - try/catch block
// const example = async () => {
// return 'hello there'
// }
// async function someFunc() {
// const result = await example()
// console.log(result)
// console.log('hello world')
// }
const users = [
{ id: 1, name: 'john' },
{ id: 2, name: 'susan' },
{ id: 3, name: 'anna' },
]
const articles = [
{ userId: 1, articles: ['one', 'two', 'three'] },
{ userId: 2, articles: ['four', 'five'] },
{ userId: 3, articles: ['six', 'seven', 'eight', 'nine'] },
]
const getData = async () => {
try {
const user = await getUser('john')
const articles = await getArticles(user.id)
console.log(articles)
} catch (error) {
console.log(error)
}
}
getData()
// getUser('susan')
// .then((user) => getArticles(user.id))
// .then((articles) => console.log(articles))
// .catch((err) => console.log(err))
function getUser(name) {
return new Promise((resolve, reject) => {
const user = users.find((user) => user.name === name)
if (user) {
return resolve(user)
} else {
reject(`No such user with name : ${name}`)
}
})
}
function getArticles(userId) {
return new Promise((resolve, reject) => {
const userArticles = articles.find((user) => user.userId === userId)
if (userArticles) {
return resolve(userArticles.articles)
} else {
reject(`Wrong ID`)
}
})
}