-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathdemo.js
58 lines (50 loc) · 1.21 KB
/
demo.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
async function defuse(ms) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(ms)
}, ms)
})
}
async function bomb(ms) {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(ms)
}, ms)
})
}
async function race() {
return Promise.race([
defuse(500 + Math.ceil(Math.random() * 500)),
bomb(800 + Math.ceil(Math.random() * 200)),
])
}
async function play() {
console.info('Game start!')
let cnt = 0
try {
while (true) {
let ms = await race()
cnt = cnt + ms
console.info(`Defuse after ${ms}ms~`)
}
} catch (msErr) {
cnt = cnt + msErr
console.info(`Bomb after ${msErr}ms~`)
}
console.info(`Game end after ${cnt}ms!`)
await {
then: function(resolve, reject) {
setTimeout(() => {
reject(this.message)
}, 1000)
},
message: 'try to throw an error :)'
}
}
Promise.resolve().then((value) => {
console.info('In next tick')
})
console.info('In main')
play().finally(() => {
console.info('Before throwing UnhandledPromiseRejection on finally!')
})