-
Notifications
You must be signed in to change notification settings - Fork 0
/
AsyncAwait.js
executable file
·70 lines (54 loc) · 1.6 KB
/
AsyncAwait.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
67
68
69
70
// ES7 Async & Await
// Description: used for make our asyns function act like sync
// Background: transpiled to function generator & yield
// Advice: mix async/await with promise for most cleaner code
// Note:
// 1. await useable only in function with async keyword
// 2. await behave similiar like .then, it return the result from promise
// 1) Simple get name and age when available both
function getName() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('pista');
}, 1000)
});
}
function getAge() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('10');
}, 2000)
});
}
async function main() {
const name = await getName();
const age = await getAge();
console.log(name, age);
}
main();
//----------------------------------------
// 2) Mix with await & Promise.all - get both result
(async function getResult() {
const [name, age] = await Promise.all([getName(), getAge()]);
console.log(name, age)
})();
//----------------------------------------
// 3) We use same example but we want catch the rejects if exist
// not, since reject is acctualy is javascript error, so you can use:
// throw 'bla', reject('bla'), Error('bla'), it is same result
async function main() {
try {
const name = await getName();
const age = await getAge();
console.log(name, age);
} catch(err) {
alert(err);
}
}
main();
//----------------------------------------
// 4) fetch is a promise, so we can use await for it
async function getData() {
const response = await (await fetch('https://jsonplaceholder.typicode.com/todos/1')).json();
console.log(response);
}