forked from codediodeio/code-this-not-that-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathasync-await.js
60 lines (44 loc) · 1004 Bytes
/
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
const random = () => {
return Promise.resolve(Math.random())
}
'Bad Promise Code 💩'
const sumRandomAsyncNums = () => {
let first;
let second;
let third;
return random()
.then(v => {
first = v;
return random();
})
.then(v => {
second = v;
return random();
})
.then(v => {
third = v;
return first + second + third
})
.then(v => {
console.log(`Result ${v}`)
});
}
'Good Promise Code ✅'
const sumRandomAsyncNums = async() => {
const first = await random();
const second = await random();
const third = await random();
console.log(`Result ${first + second + third}`);
if (await random()) {
// do something
}
const randos = Promise.all([
random(),
random(),
random()
])
for(const r of await randos) {
console.log(r)
}
}
sumRandomAsyncNums()