js|es6Generator(Function)使用指南

GeneratorFunction和Gernerator的关系就像function和object的关系一样。Generator是使用GeneratorFunctijon创建出来的对象,而GeneratorFunction的创建类似于function的创建,只是在function关键字后面多了个星号,在使用GeneratorFunction中使用yield关键字来分段,Generator调用next方法来执行。看下面例子

分段执行测试

<script>
	function *Schedule() {
		console.log("Start");
		var msg = "起床";
		yield console.log(msg);
		var msg = "洗漱";
		yield console.log(msg);
		var msg = "做饭";
		yield console.log(msg);
		var msg = "吃饭";
		yield console.log(msg);
		var msg = "上班";
		yield console.log(msg);
		
	};
	var schedule = Schedule();
	schedule.next();
	schedule.next();
	schedule.next();
	schedule.next();
	schedule.next();
</script>

在这里插入图片描述
分段执行的绝佳好例子,其中Start是在next执行完毕后,跟起床一起执行的哟,需要注意!

返回值测试

它的返回值是IteratorResult,这个大家应该不会陌生,主要玩的是value和done,再看一例子

测试代码

<script>
	function *Add(arg) {
		var a = yield arg;
		console.log(a);
		var b = yield a+arg;
		console.log(b);
		var c = yield b+arg;
		console.log(c);								
	}
	var g = Add(50);
	var result = g.next();
	console.log(JSON.stringify(result));
	result = g.next(1);
	console.log(JSON.stringify(result));
	result = g.next(2);
	console.log(JSON.stringify(result));
	result = g.next(3);
	console.log(JSON.stringify(result));
</script>

测试效果

在这里插入图片描述
这个代码不断地进行数据获得,最后遍历返回,最后发现done为true。true大家都能明白是其执行完毕的意思,而false就是没有执行完毕。

剩余方法测试

它本身还有两个方法一个是return和throw,字面意思throw抛异常,如果有错误外部给内部抛出异常,return就是结束所有分段执行,拿取一例细细体味就能理解

测试代码

<script>
	function *Add(arg) {
		try{
		var a = yield arg;
		console.log(a);
		var b = yield a+arg;
		console.log(b);
		var c = yield b+arg;
		console.log(c);						
		}catch(e){
			//TODO handle the exception
			console.log(`出错了,错误原因:${e}`);
		}
	}
	var add1 = Add(30);
	var result = add1.next();
	console.log(JSON.stringify(result));
	console.log(JSON.stringify(result));
	result = add1.throw("over");
	console.log(JSON.stringify(result));

	var add2 = Add(30);
	var result = add2.next();
	console.log(JSON.stringify(result));
	var result = add2.next(1);
	console.log(JSON.stringify(result));
	result = add1.return("result");
	console.log(JSON.stringify(result));
</script>

测试效果

在这里插入图片描述
我们用throw将其抛出异常,用return将其认为结束分段执行,done也变成true。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值