Async/Await 实现原理

Async是什么

Async 实现原理

Async 是对Generator的一个升级

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
async function fn(args) {
// ...awiat
}

// 等价于

function fn(args) {
return spawn(function* () {

});
}


function spawn(genF) {
return new Promise(function(resolve, reject) {
const gen = genF();
function step(nextF) {
let next;
try {
next = nextF();
} catch (e) {
return reject(e);
}
if (next.done) {
return resolve(next.value);
}

Promise.resolve(next.value)
.then(function(v) {
step(function() {
return gen.next(v);
})
}, function(v) {
step(function() {
return gen.throw(e);
})
});
}
step(function() {
return gen.next(undefined);
});
})
}

Babel 如何对Async 做的编译

参考抽象语法树1: https://juejin.im/post/5c8d3c48f265da2d8763bdaf#heading-12
参考文档2: https://segmentfault.com/a/1190000015653342#articleHeader24

  • Babel 通过Babylon(Babel parser) 将async经过词法分析&语法分析后输出AST(抽象语法树) 结构如下
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
async function fn(args) {
const t = await 1;
return t;
}

// 可以通过esprima 分析工具查看: http://esprima.org/demo/parse.html#
// 所有节点都会实现以下接口
interface Node {
type: string;
range?: [number, number];
loc? SourceLocation;
}

interface SourceLocation {
start: Position;
end: Position;
source?: string | null;
}

interface Position {
line: uint32 >= 1;
column: uint32 >= 0;
}
// type: FunctionDeclaration 函数声明的抽象树实现以下接口
interface FunctionDeclaration {
type: 'FunctionDeclaration';
id: Identifier || null;
params: FunctionParameter[];
body: BlockStatement;
generator: boolean;
async: boolean;
expression: false;
}

// AST 结构
{
type: 'Program',
sourceType: 'script',
body: [
{
type: 'FunctionDeclaration',
id: {
type: 'Identifier',
name: 'fn'
},
params: [
{
type: 'Identifier',
name: 'args'
}
],
body: {
type: 'BlockStatement',
body: [
{
type: 'VariableDeclaration',
declarations: [
{
type: 'Identifier',
name: 't
}
],
init: {
type: 'AwaitExpression',
argument: {
type: 'Literal',
value: 1,
raw: 1
}
},
kind: 'const'
},
{
type: 'ReturnStatement',
'argument': {
type: 'Identifier',
name: 't'
}
}
]
},
generator: false,
expression: false,
async: true
}
]
}
  • 根据 type: ‘FunctionDeclaration’, async: true 将函数转成Generator函数
  • 将Generator函数AST, 编译成ES5代码