基本概念
Generator 函数是 ES6 提供的一种异步编程解决方案,语法行为与传统函数完全不同。
generator函数和普通函数的区别
function* helloWorldGenerator() {
yield 'hello';
yield 'world';
return 'ending';
}
var hw = helloWorldGenerator();
特征上的区别
function后面跟*
内部可以使用yield表达式
执行和执行后的区别
Generator 函数的调用方法与普通函数一样,也是在函数名后面加上一对圆括号。
不同的是,调用 Generator 函数后,该函数并不执行。返回一个符合可迭代协议的对象
next函数
console.log(hw.next())
console.log(hw.next())
console.log(hw.next())
console.log(hw.next())
/* {value: 'hello', done: false}
{value: 'world', done: false}
{value: 'ending', done: true}
{value: undefined, done: true} */
执行next函数 Generator函数开始执行,直到遇到yield表达式位置,next方法
会返回一个对象{value: 'hello', done: false} value的值时当前yield
的值,done为false表示遍历还没有结束,为true遍历结束。
yield表达式
hw.next()
当遇到yield表达式后,函数就暂停执行,yield表达式紧跟的值为返回对象的value值,
下一次调用next继续往下执行,直到遇到下一个yield表达式
next 方法的参数
function* f() {
for(var i = 0; true; i++) {
var reset = yield i;
if(reset) { i = -1; }
}
}
var g = f();
g.next()
g.next()
g.next(true)
throw方法和return()方法
hw.throw(1)
hw.return('foo')
yield* 表达式
function* foo() {
yield 'a';
yield 'b';
}
function* bar() {
yield 'x';
yield* foo();
yield 'y';
}
function* bar() {
yield 'x';
yield 'a';
yield 'b';
yield 'y';
}