概述
Generator是ES6提供的一种异步编程解决方案,语法行为与传统函数完全不同。执行Generator函数会返回一个遍历器对象,返回的遍历器对象可以依次遍历Generator函数内部的每一个状态。function关键字与函数名之间有一个星号;函数体内部使用yield表达式,定义不同的内部状态。- 调用
Generator函数后,该函数并不执行,返回的也不是函数运行结果,而是一个指向内部状态的指针对象,也就是Iterator对象。接着需要调用next方法使得指针移向下一个状态。每次调用next方法,内部指针就从函数头部或上一次停下来的地方开始执行,直到遇到下一个yield表达式或return。
function* helloWorldGenerator() {
yield 'hello';
yield 'world';
return 'ending';
}
let iter = helloWorldGenerator()
iter.next() // {value: 'hello', done: false}
iter.next() // {value: 'world', done: false}
iter.next() // {value: 'ending', done: true}
yield表达式
-
由于
Generator函数返回的遍历器对象,只有调用next方法才会遍历下一个内部状态,所以其实提供了一种可以暂停执行的函数。yield表达式就是暂停标志。运行逻辑如下:- 遇到
yield表达式,就暂停执行后面的操作,并将紧跟在yield后面的那个表达式的值,作为返回的对象的value属性值。 - 下一次调用
next方法时,再继续往下执行,直到遇到下一个yield表达式。 - 如果没有再遇到新的
yield表达式,就一直运行到函数结束,直到return语句为止。并将return语句后面的表达式的值作为返回的对象的value属性值。如果该函数没有return语句,则返回的对象的value值为undefined。
- 遇到
-
Generator函数可以不用yield表达式,这时就变成了一个单纯的暂缓执行函数。
function* f() {
console.log('执行了!')
}
var generator = f();
setTimeout(function () {
generator.next() // 执行了!
}, 2000);
yield表达式只能用在Generator函数中,用在其他地方会报错。
(function (){
yield 1;
})()
// SyntaxError: Unexpected number
yield表达式如果用在另一个表达式之中,必须放在圆括号里面。
function* demo() {
console.log('Hello' + yield); // SyntaxError
console.log('Hello' + yield 123); // SyntaxError
console.log('Hello' + (yield)); // OK
console.log('Hello' + (yield 123)); // OK
}
与Iterator接口的关系
- 任意一个对象的
Symbol.iterator方法,等于该对象的遍历器生成函数,调用该函数会返回该对象的一个遍历器对象。由于Generator函数就是遍历器生成函数,因此可以把Generator赋值给对象的Symbol.iterator属性,从而使得该对象具有Iterator接口。
var obj = {};
// 给obj普通对象添加了Symbol.iterator属性,
// 从此obj具有了Iterator接口,可以被扩展运算符遍历了
obj[Symbol.iterator] = function* (){
yield 1;
yield 2;
yield 3;
}
[...obj] // [1, 2, 3]
Generator函数会返回一个遍历器对象,这个对象的Symbol.iterator就是指向这个对象自身。
function* gen(){
// some code
}
var g = gen();
g[Symbol.iterator]() === g // true
for of循环
for...of循环可以自动遍历 Generator 函数运行时生成的Iterator对象,且此时不再需要调用next方法。
function* foo() {
yield 1;
yield 2;
yield 3;
yield 4;
yield 5;
return 6;
}
for (let v of foo()) {
console.log(v);
}
// 1 2 3 4 5
return的返回值,不包括在for of循环中。
next()
yield表达式本身没有返回值,或者说总是返回undefined。next方法可以带一个参数,该参数就会被当作上一个yield表达式的返回值。
function* foo(x) {
var y = 2 * (yield(x + 1));
var z = 5 + (yield(y / 3));
return (x + y + z);
}
// ----------------------------------next()未传参数---------------------------------------
var a = foo(5);
// 执行的(x + 1)表达式,返回 6
a.next() // {value: 6, done: false}
// 未传参数,导致 y 的值为 2 * undefined,等于NaN,执行( y / 3),返回NaN
a.next() // {value: NaN, done: false}
// 未传参数,导致 z 的值为 5 + undefined,等于NaN,执行(x + y + z),等于(5 + NaN + NaN),返回NaN
a.next() // {value: NaN, done: true}
// ----------------------------------next()传参数---------------------------------------
var b = foo(5);
// 执行的(x + 1)表达式,返回 6
b.next() // {value: 6, done: false}
// 传了参数,导致 y 的值为 2 * 15,执行 (30 / 3),返回10
b.next(15) // {value: 10, done: false}
// 传了参数,导致 z 的值为 5 + 10,执行(x + y + z)等于(5 + 30 + 15)
b.next(10) // {value: 50, done: true}
throw()
- Generator 函数返回的遍历器对象,都有一个
throw方法,可以在函数体外抛出错误,然后在 Generator 函数体内捕获。被内部捕获以后,等同于执行了一次next方法,也不会不影响下一次遍历。 throw方法可以接受一个参数,该参数会被catch语句接收。
var g = function* () {
try {
console.log(1 + 2); // 3
yield;
} catch (e) {
console.log(e); // Error: 出错了!
}
};
var i = g();
i.next();
i.throw(new Error('出错了!'));
- 如果Generator函数内部没有部署
try...catch代码块,那么throw方法抛出的错误,将被外部try...catch代码块捕获。
var g = function* () {
while (true) {
yield;
console.log('内部捕获', e);
}
};
var i = g();
i.next();
try {
i.throw('a');
i.throw('b');
} catch (e) {
console.log('外部捕获', e); // 外部捕获 a
}
- 如果 Generator 函数内部和外部,都没有部署
try...catch代码块,那么程序将报错,直接中断执行。
return()
- 返回给定的值,并且终结遍历 Generator 函数。如果不提供参数,则返回值的
value属性为undefined。
function* gen() {
yield 1;
yield 2;
yield 3;
}
var g = gen();
g.next() // { value: 1, done: false }
g.return('foo') // { value: "foo", done: true } 终止运行,done变为了true
g.next() // { value: undefined, done: true } 后续再次调用 value都是undefined,done都是true
yield*表达式
- 如果在 Generator 函数A内部,调用另一个 Generator 函数B。需要在A的函数体内部,自己手动完成遍历函数B。
function* foo() {
yield 'a';
yield 'b';
}
function* bar() {
yield 'x';
// 手动遍历 foo()
for (let i of foo()) {
console.log(i);
}
yield 'y';
}
for (let v of bar()){
console.log(v);
}
// x
// a
// b
// y
- ES6提供了
yield*表达式,作为解决办法,用来在一个 Generator 函数里面执行另一个 Generator 函数。实际上,任何数据结构只要有Iterator接口,就可以被yield*遍历。
function* foo() {
yield 'a';
yield 'b';
}
// yield*写法
function* bar() {
yield 'x';
yield* foo();
yield 'y';
}
// 等同于
function* bar() {
yield 'x';
// 手动遍历 foo()
for (let i of foo()) {
console.log(i);
}
yield 'y';
}
// "x"
// "a"
// "b"
// "y"
- 如果被代理的 Generator 函数有
return语句,那么就可以向代理它的 Generator 函数返回数据。
function* foo() {
yield 2;
yield 3;
return "foo";
}
function* bar() {
yield 1;
var v = yield* foo(); // 可以接收返回值
console.log("v: " + v);
yield 4;
}
var it = bar();
it.next()
// {value: 1, done: false}
it.next()
// {value: 2, done: false}
it.next()
// {value: 3, done: false}
it.next();
// "v: foo"
// {value: 4, done: false}
it.next()
// {value: undefined, done: true}
Generator作为对象属性
let obj = {
* myGeneratorMethod() {
···
}
};