ES6语法之 Generator 函数

概念:

Generator 函数是 ES6 提供的异步解决方法,可以把 Generator 函数看成是一种状态机,其内部封装了多种状态。执行 Generator 函数会返回一个遍历器对象,所以Generator 函数也是一个遍历器对象生成函数

特点:

1.在写法上比普通函数在function后面多了一个*;

//普通函数
function a(){}
//Generator 函数
function* a(){} //注意这里的function后面多了一个*

2.函数内部使用 yield 表达式,执行函数时通过 next 方法获取内部状态(这里的 yield 表示暂停,调用 next 方法表示放行);

function* gen(){
yield 1;
yield 2;
return 3
};
var iterator = gen();//得到遍历器对象;
iterator.next();//{value:1,done:false};
iterator.next();//{value:2,done:false};
iterator.next();//{value:3,done:true};

3.调用 Generator 函数返回一个遍历器,可通过 for of 遍历出内部所有状态(return 后面的值会返回undefined)。

function* gen(){
yield 1;
yield 2;
return 3
};
var iterator = gen();//得到遍历器对象;
for(var i of iterator){
console.log(i)//1 2 undefined
}

应用:

1.由于 Generator 函数是一种状态机机制,可以用于状态控制,下面演示了一个非红即黑状态的例子;

//非Generator函数
var bool = true;
function state(){
if(bool){
console.log('red');
}else{
console.log('black');
}
bool = !bool;
};
state()//red;
state()//black;
...

//Generator函数
function* gen(){
while(true){
console.log('red');
   yield;
console.log('black');
   yield;
}
};
var iterator = gen();
iterator.next()//red;
iterator.next()//black;
...

2.异步的操作可以写成同步的流程。

//非 Generator 函数
function gen(){
setTimeout(function(){console.log(111)},2000);
console.log(222);
};
gen();//222 111

//Generator 函数
function* gen(){
yield setTimeout(function(){console.log(111)},2000);
console.log(222);
};
var y= gen();
y.next();//111;
y.next();//222

猜你喜欢

转载自blog.csdn.net/weixin_44135121/article/details/89198673