-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDemo13_async_await.js
98 lines (76 loc) · 1.81 KB
/
Demo13_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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/**
* * Async ... Await ~ Promise
*/
'use strict'
console.clear()
//? Promise
const resolveAfter2MilliSecond = () => {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved')
}, 2);
})
}
// resolveAfter2Second()
// .then(data => {
// console.log(data)
// })
async function asyncCall() {
console.log("Calling")
const result = await resolveAfter2MilliSecond()
console.log(result)
console.log("DONE")
console.log("------------------------------")
}
console.log("STARTING")
asyncCall()
console.log("COMPLETED")
//? Async is similar Promise. Await must be waiting here
async function foo() {
return 1
}
// function foo() {
// return Promise.resolve(1)
// }
//? Compare Async with Promise
const p = new Promise((resolve, reject) => {
resolve(1)
})
async function a() {
return p
}
function basic() {
return Promise.resolve(p)
}
console.log(p === basic())
console.log(p === a())
/**
* async function foo() {
* await 1
* }
*
* function foo() {
* return Promise.resolve(1).then(() => undefine)
* }
*/
async function f_sequence_1() {
const result_1 = await new Promise(resolve => {
console.log('result_1 is called')
setTimeout(() => resolve('1'))
})
const result_2 = await new Promise(resolve => {
console.log('result_2 is called')
setTimeout(() => resolve('2'))
})
}
f_sequence_1()
async function f_sequence_2() {
const result_1 = new Promise((resolve) => setTimeout(() => resolve('1'), 1000))
const result_2 = new Promise((resolve,reject) => setTimeout(() => reject('2'), 500))
const result = [await result_1, await result_2]
}
f_sequence_2()
.then(data => console.log(data))
.catch(error => {
console.log("=> ERROR", error)
})