文章结构
生成器函数的定义与使用
给生成器函数传参
给生成器函数异步传参
生成器函数的应用场景
解决回调地域
1 //生成器函数的定义与使用 2 function *fn(){ 3 //yield类似于断电 4 console.log(111); 5 yield `第一段` 6 console.log(222); 7 yield `第二段` 8 console.log(333); 9 yield `第三段` 10 console.log(444); 11 } 12 13 //调用 14 let iterator = fn(); 15 //每次调用next会执行生成器函数中yield段代码,并且返回包含yield的值的对象 16 console.log(iterator.next()); 17 console.log(iterator.next()); 18 console.log(iterator.next()); 19 console.log(iterator.next()); 20 21 for(let i of fn()){ 22 console.log(i); 23 }
给生成器函数传参
1 function * fn(arg){ 2 console.log(arg); 3 let one = yield 1; 4 console.log(one); 5 let two = yield 2; 6 console.log(two); 7 let three = yield 3; 8 console.log(three); 9 } 10 11 //执行获取迭代器对象 12 let iterator = fn('AAA'); 13 iterator.next(); 14 //从第二次开始next的参数会成为yield的返回值 15 iterator.next('BBB'); 16 iterator.next('CCC'); 17 iterator.next('DDD');
给生成器函数异步传参
1 function getname() { 2 setTimeout(() => { 3 let name = 'zhangsan'; 4 iterator.next(name); 5 }, 1000) 6 } 7 8 function getdata() { 9 setTimeout(() => { 10 let data = 'data'; 11 iterator.next(data); 12 }, 2000) 13 } 14 15 function gettime() { 16 setTimeout(() => { 17 let time = 'time'; 18 iterator.next(time); 19 }, 3000) 20 } 21 22 function* fn() { 23 getname(); 24 // 可以使用一个变量去接收yield的返回值,yield返回上一次调用iterator.next()的参数 25 let one = yield; 26 console.log(one); 27 getdata(); 28 let two = yield; 29 console.log(two); 30 gettime(); 31 let three = yield; 32 console.log(three); 33 } 34 35 let iterator = fn(); 36 iterator.next();
生成器函数的应用场景
解决回调地域
1 setTimeout(() => { 2 console.log(111); 3 setTimeout(() =>{ 4 console.log(222); 5 setTimeout(()=>{ 6 console.log(333) 7 },3000) 8 },2000) 9 },1000) 10 11 function fn1(){ 12 setTimeout(()=>{ 13 console.log(111); 14 iterator.next(); 15 },1000) 16 } 17 18 function fn2(){ 19 setTimeout(()=>{ 20 console.log(222); 21 iterator.next(); 22 },1000) 23 } 24 25 function fn3(){ 26 setTimeout(()=>{ 27 console.log(333); 28 iterator.next(); 29 },1000) 30 } 31 32 function *fn(){ 33 fn1(); 34 yield; 35 fn2(); 36 yield; 37 fn3(); 38 yield; 39 } 40 41 let iterator = fn(); 42 iterator.next();
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/282567.html