es6的生成器函数

  1. 生成器函数也是一种异步编程的解决方案,与普通函数不同的是函数名前有*,通过yield将函数体分成多个区域,且是通过.next()调用的

    function *show() {
    	console.log('第一个代码块');
    	yield '1';
    	console.log('第二个代码块');
    	yield '2';
    	console.log('第三个代码块');
    	yield '3';
    	console.log('第四个代码块');
    }
    const iterator = show();
    iterator.next(); // 执行第一个代码块
    iterator.next(); // 执行第二个代码块
    iterator.next(); // 执行第三个代码块
    iterator.next(); // 执行第四个代码块
    
  2. 适用场景:等到某段代码执行完之后才执行另一段代码的时候

  3. next方法可传递参数(next参数将作为上一个yield的返回结果)

    function *show() {
    	console.log('第一个代码块');
    	const result1 = yield '1';
    	console.log(result1);
    	console.log('第二个代码块');
    	const result2 = yield '2';
    	console.log(result2);
    	console.log('第三个代码块');
    	const result3 = yield '3';
    	console.log(result3);
    	console.log('第四个代码块');
    }
    const iterator = show();
    iterator.next(); // 执行第一个代码块
    iterator.next('参数1'); // 执行第二个代码块
    iterator.next('参数2'); // 执行第三个代码块
    iterator.next('参数3'); // 执行第四个代码块
    
  4. 案例:1s后输出hello,2s后输出world,3s后输出aaa

    function hello() {
    	setTimeout(() => {
    		console.log('hello');
    		iterator.next();
    	}, 1000);
    }
    function world() {
    	setTimeout(() => {
    		console.log('world');
    		iterator.next();
    	}, 2000);
    }
    function aaa() {
    	setTimeout(() => {
    		console.log('aaa');
    		iterator.next();
    	}, 3000);
    }
    function *show() {
    	yield hello();
    	yield world();
    	yield aaa();
    }
    const iterator = show();
    iterator.next();
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值