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。