generator生成器
邵预鸿 Lv5

generator开始

1
2
3
4
5
6
7
8
9
10
11
12
13
<script>
function *g(){
console.log('g fn is start');
yield;
console.log('console.log b is start');
yield;
console.log('end')
}
var generator = g();
generator.next(); //g fn is start [yield会像return一样返回值,{value: undefined, done: false}]
generator.next(); // console.log b is start [yield会像return一样返回值,{value: undefined, done: false}]
generator.next(); //end [yield会像return一样返回值,{value: undefined, done: true}]
</script>

generator生成器是用法和普通函数相同,遇到yield暂停,使用next将执行一下yeild

done为true时,当前generator生成器执行完成

generator next传参与执行顺序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<script>
function *g(defaultValue){
console.log(defaultValue);
console.log('g fn is start');
const nextValue1 = yield 'yield1 result';
console.log('nextValue1=',nextValue1)
console.log('console.log b is start');
const nextValue2 = yield 'yield2 result';
console.log('nextValue2=',nextValue2);
console.log(defaultValue);
console.log('end');
return 'function end'; //如果有return res3.value就有值,没有return res3.value的值是空的undefind
}
var generator = g('default');
const res1 = generator.next();
console.log('res1:',res1);
const res2 = generator.next('100');
console.log('res2:',res2);
const res3 = generator.next(200);
console.log('res3:',res3);
</script>

default
g fn is start
res1: {value: ‘yield1 result’, done: false}
nextValue1= 100
console.log b is start
res2: {value: ‘yield2 result’, done: false}
nextValue2= 200
default
end
res3: {value: ‘function end’, done: true}

如何更好理解上面的执行打印结果

先简化一下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function *g(defaultValue){
/* const nextValue1 = yield 'yield1 result';
console.log('nextValue1=',nextValue1)
console.log('console.log b is start');
*/

/* =======以上代码等同于===========*/
1. 返回 'yield1 result'
2. yield 并执行到当前这里
3. const nextValue1 = next传递的参数
所以nextValue1的值其实是在下一个next中执行的
}
var generator = g('default');
const res1 = generator.next();
console.log('res1:',res1);
const res2 = generator.next('100');
console.log('res2:',res2);

解决回调地狱问题

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
function request(count){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
const result = count+1;
resolve(result);
},1000)
});
}

function *g(defaultCount){
const count1 = yield request(defaultCount);
console.log('count1:',count1)


const count2 = yield request(count1);
console.log('count2:',count2)


const count3 = yield request(count2);
console.log('count3:',count3)


const count4 = yield request(count3);
console.log('count4:',count4)

return count4;
}

var g1 = g(1);
function run(count= null){
const promiseFn = g1.next(count);
if(!promiseFn.done){
promiseFn.value.then(res=>{
run(res);
})
}

}
run();

输出结果为每等待1S输出一个结果 :

count1: 2
count2: 3
count3: 4
count4: 5

  • 本文标题:generator生成器
  • 本文作者:邵预鸿
  • 创建时间:2022-06-13 06:15:26
  • 本文链接:/images/logo.jpg2022/06/13/generator生成器/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!