# ❓Async/Await 如何通过同步的方式实现异步?
这要讲一讲 Async
的实现原理,就是将 Generator
函数和自动执行器,包装在一个函数里面。
async function fnName(args) {
// ...
}
// 等同于
function fnNameB() {
return spawn(function*() {
// ...
});
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
所有的 async
函数我们都可以写成上面代码中的第二种形式,其中 spawn
函数就是自动执行期。
// 接收一个 generator 函数参数
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(e) {
step(function() {
return gen.throw(e);
});
}
);
}
// 自动执行
step(function() {
return gen.next(undefined);
});
});
}
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
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
spawn
函数内部还是利用了 promise
实现的异步模式。