生成器函数是es6提供的一种异步编程解决方案,语法行为与传统函数不同。以前完成异步操作方式是回调函数。
1.在声明的时候,在function与函数名之间有一个*
2.在调用的时候:不能直接调用,要使用next方法才能调用(不能直接调用,因为生成器函数默认的状态为暂停suspend)
function * gen() {
console.log(函数执行了);
}
let iterator = gen(); console.log(iterator);//这个生成器函数,实际上是一个迭代器对象
iterator.next()
3.在生成器函数中,可以出现yeild语句,出现的作用是,将函数内部由n个yeild分割成n+1个块。(需要注意的是yeild语句只能在生成器函数中使用)
举例:
function * gen(){
console.log(‘执行第一个模块’);
yield ‘第一个分割’
console.log(‘执行第二个模块’);
yield ‘第二个分割’
console.log(‘执行第三个模块’);
yield ‘第三个分割’
console.log(‘执行第四个模块’)
}
let iterator = gen();
iterator.next();
iterator.next();
iterator.next();
iterator.next();
使用for…of语句遍历生成器函数:
function * gen(){
console.log(‘执行第一个模块’);
yield ‘第一个分割’
console.log(‘执行第二个模块’);
yield ‘第二个分割’
console.log(‘执行第三个模块’);
yield ‘第三个分割’
console.log(‘执行第四个模块’)
}
for(const v of gen()) {
console.log(v);
}
控制台打印调用结果:
function * gen(){
console.log(‘执行第一个模块’);
yield ‘第一个分割’
console.log(‘执行第二个模块’);
yield ‘第二个分割’
console.log(‘执行第三个模块’);
yield ‘第三个分割’
console.log(‘执行第四个模块’)
}
let iterator = gen()
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
注意:上面打印函数的调用结果,object为yield语句的执行结果,返回的value是yield后面的值,返回的done是判断yield语句是否执行完。
如果对于一个空的生成器函数调用next()方法,返回的结果Object中done: true, value: underfined;