Generator 函数概述
- 遇到yield表达式,就暂停执行后面的操作,并将yield表达式的值作为value
- 每次调用next方法,内部指针就从函数头部或上一次停下来的地方开始执行,直到遇到下一个yield表达式(或return语句)为止
- Generator 函数是分段执行的,yield表达式是暂停执行的标记,而next方法可以恢复执行
写法
- Generator 函数是一个普通函数,function关键字与函数名之间有一个星号
- ES6 没有规定,function关键字与函数名之间的星号,写在哪个位置。这导致下面的写法都能通过
function * foo(x, y) { ··· }
function *foo(x, y) { ··· }
function* foo(x, y) { ··· }
function*foo(x, y) { ··· }
代码示例
value
:当前yield表达式的值done
:遍历是否已结束
function* helloWorldGenerator() {
console.log(1)
yield 'hello';
console.log(2)
yield 'world';
console.log(3)
return 'ending';
}
var hw = helloWorldGenerator();
hw.next()
hw.next()
hw.next()
hw.next()
执行解析
- 第1次next执行代码
console.log(1)
yield 'hello';
- 第2次next执行代码
console.log(2)
yield 'world';
- 第3次next执行代码
console.log(3)
return 'ending';
- 第4次next执行代码
在第三次next
时,done
变为true
,表示函数已经运行完毕
第四次以及之后再调用next
方法,返回的都是这个值{ value: undefined, done: true }