-
-
Notifications
You must be signed in to change notification settings - Fork 100
/
Copy pathevent-loop.js
85 lines (45 loc) · 1.26 KB
/
event-loop.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
/*
* @Author : OBKoro1
* @Date : 2021-09-10 11:14:30
* LastEditors : OBKoro1
* LastEditTime : 2021-09-11 16:39:02
* FilePath : /js-base/src/scene/ecent-loop.js
* @description : 实战event-loop任务优先级
* 掌握这些任务的优先级:setTimeout、promise.nextTick、setImmediate、promise、
* koroFileheader VSCode插件
* Copyright (c) 2021 by OBKoro1, All Rights Reserved.
*/
//
// 答案在下面
setImmediate(() => {
console.log(1)
}, 0)
setTimeout(() => {
console.log(2)
}, 0)
new Promise((resolve) => {
console.log(3)
resolve()
console.log(4)
}).then(() => {
console.log(5)
})
async function test() {
const a = await 9
console.log(a)
const b = await new Promise((resolve) => {
resolve(10)
})
console.log(b)
}
test()
console.log(6)
process.nextTick(() => {
console.log(7)
})
console.log(8)
// 微任务:nextTick比then优先级高 宏任务:setTimeout优先级比setImmediate高
// process.nextTick > promise.then > setTimeout > setImmediate
// 注意await也是promise 但是需要一个个promise添加进去 所以同一个await里面的promise的顺序可能被其他的promise插队
// 解析:https://www.jianshu.com/p/a39d3e878d06
// 答案:3 4 6 8 7 5 2 1