generator方法

再简单复习一下,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
44
45
46
function step1 (success) {
setTimeout(() => {
console.log('step1');
success();
}, 1000);
}

function step2 (success) {
setTimeout(() => {
console.log('step2');
success();
}, 1000);
}

function step3 (success) {
setTimeout(() => {
console.log('step3');
success();
}, 1000);
}

function* main () {
// generator 配合yield和next来实现异步编程,
// yield让函数等待上一个执行完后再执行,next()让执行指针跳到下下一个

yield step1;
yield step2;
yield step3;
}

function run (fn) {
/**
* 在fn,也就是main这个generator函数执行完后,会返回一个generator
* .next后会返回下一个yield等待执行的信息,一个对象{done: false value: ƒ step1()}
* 那么我们通过,这个对象中的done来判断,这个generator是否执行完成(false表示后面还有一不代码要执行)
*/
let gen=fn()
function next (){
let result = gen.next();
console.log(result)
if (result.done) return
result.value(next);
}
next();
}
run (main)

输出

Share
2 min. read