function* helloWorldGenerator() { yield 'hello'; yield 'world'; return 'ending'; } var hw = helloWorldGenerator();
上面代码定义了一个 Generator 函数helloWorldGenerator,它内部有两个yield表达式(hello和world),即该函数有三个状态:hello,world 和 return 语句(结束执行)。编程
而后,Generator 函数的调用方法与普通函数同样,也是在函数名后面加上一对圆括号。不一样的是,调用 Generator函数后,该函数并不执行,返回的也不是函数运行结果,而是一个指向内部状态的指针对象。数组
下一步,必须调用遍历器对象的next方法,使得指针移向下一个状态。也就是说,每次调用next方法,内部指针就从函数头部或上一次停下来的地方开始执行,直到遇到下一个yield表达式(或return语句)为止。换言之,Generator 函数是分段执行的,yield表达式是暂停执行的标记,而next方法能够恢复执行。安全
hw.next() // { value: 'hello', done: false } hw.next() // { value: 'world', done: false } hw.next() // { value: 'ending', done: true } hw.next() // { value: undefined, done: true }
上面代码一共调用了四次next方法:数据结构
总结一下,调用 Generator 函数,返回一个遍历器对象,表明 Generator 函数的内部指针。之后,每次调用遍历器对象的next方法,就会返回一个有着value和done两个属性的对象。value属性表示当前的内部状态的值,是yield表达式后面那个表达式的值;done属性是一个布尔值,表示是否遍历结束。异步
因为 Generator 函数返回的遍历器对象,只有调用next方法才会遍历下一个内部状态,因此其实提供了一种能够暂停执行的函数。yield表达式就是暂停标志。函数式编程
遍历器对象的next方法的运行逻辑以下:函数
须要注意的是,yield表达式后面的表达式,只有当调用next方法、内部指针指向该语句时才会执行,所以等于为 JavaScript 提供了手动的“惰性求值”(Lazy Evaluation)的语法功能:this
function* gen() { yield 123 + 456; }
上面代码中,yield后面的表达式123 + 456,不会当即求值,只会在next方法将指针移到这一句时,才会求值。lua
yield表达式与return语句既有类似之处,也有区别。类似之处在于,都能返回紧跟在语句后面的那个表达式的值。区别在于每次遇到yield,函数暂停执行,下一次再从该位置继续向后执行,而return语句不具有位置记忆的功能。一个函数里面,只能执行一次(或者说一个)return语句,可是能够执行屡次(或者说多个)yield表达式。正常函数只能返回一个值,由于只能执行一次return;Generator 函数能够返回一系列的值,由于能够有任意多个yield。url
另外须要注意,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 }
yield表达式用做函数参数或放在赋值表达式的右边,能够不加括号:
function* demo() { foo(yield 'a', yield 'b'); // OK let input = yield; // OK }
任意一个对象的Symbol.iterator方法,等于该对象的遍历器生成函数,调用该函数会返回该对象的一个遍历器对象。
因为 Generator 函数就是遍历器生成函数,所以能够把 Generator 赋值给对象的Symbol.iterator属性,从而使得该对象具备 Iterator 接口
var myIterable = {}; myIterable[Symbol.iterator] = function* () { yield 1; yield 2; yield 3; }; [...myIterable] // [1, 2, 3]
上面代码中,Generator函数赋值给Symbol.iterator属性,从而使得myIterable对象具备了 Iterator 接口,能够被...运算符遍历了。
Generator 函数执行后,返回一个遍历器对象。该对象自己也具备Symbol.iterator属性,执行后返回自身:
function* gen(){ // some code } var g = gen(); g[Symbol.iterator]() === g // true
上面代码中,gen是一个 Generator 函数,调用它会生成一个遍历器对象g。它的Symbol.iterator属性,也是一个遍历器对象生成函数,执行后返回它本身。
yield表达式自己没有返回值,或者说老是返回undefined。next方法能够带一个参数,该参数就会被看成上一个yield表达式的返回值。
function* foo(x) { var y = 2 * (yield (x + 1)); var z = yield (y / 3); return (x + y + z); } var a = foo(5); a.next() // Object{value:6, done:false} a.next() // Object{value:NaN, done:false} a.next() // Object{value:NaN, done:true} var b = foo(5); b.next() // { value:6, done:false } b.next(12) // { value:8, done:false } b.next(13) // { value:42, done:true }
这个功能有很重要的语法意义。Generator函数从暂停状态到恢复运行,它的上下文状态(context)是不变的。经过next方法的参数,就有办法在Generator函数开始运行以后,继续向函数体内部注入值。也就是说,能够在Generator函数运行的不一样阶段,从外部向内部注入不一样的值,从而调整函数行为。
注意,因为next方法的参数表示上一个yield表达式的返回值,因此在第一次使用next方法时,传递参数是无效的。V8引擎直接忽略第一次使用next方法时的参数,只有从第二次使用next方法开始,参数才是有效的。从语义上讲,第一个next方法用来启动遍历器对象,因此不用带有参数。
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
上面代码使用for...of循环,依次显示5个yield表达式的值。这里须要注意,一旦next方法的返回对象的done属性为true,for...of循环就会停止,且不包含该返回对象,因此上面代码的return语句返回的6,不包括在for...of循环之中
利用for...of循环,能够写出遍历任意对象(object)的方法。原生的 JavaScript 对象没有遍历接口,没法使用for...of循环,经过 Generator 函数为它加上这个接口,就能够用了:
function* objectEntries() { let propKeys = Object.keys(this); for (let propKey of propKeys) { yield [propKey, this[propKey]]; } } let jane = { first: 'Jane', last: 'Doe' }; jane[Symbol.iterator] = objectEntries; for (let [key, value] of jane) { console.log(`${key}: ${value}`); } // first: Jane // last: Doe
除了for...of循环之外,扩展运算符(...)、解构赋值和Array.from方法内部调用的,都是遍历器接口。这意味着,它们均可以将 Generator 函数返回的 Iterator 对象,做为参数:
function* numbers () { yield 1 yield 2 return 3 yield 4 } // 扩展运算符 [...numbers()] // [1, 2] // Array.from 方法 Array.from(numbers()) // [1, 2] // 解构赋值 let [x, y] = numbers(); x // 1 y // 2 // for...of 循环 for (let n of numbers()) { console.log(n) } // 1 // 2
Generator 函数返回的遍历器对象,都有一个throw方法,能够在函数体外抛出错误,而后在 Generator 函数体内捕获
var g = function* () { try { yield; } catch (e) { console.log('内部捕获', e); } }; var i = g(); i.next(); try { i.throw('a'); i.throw('b'); } catch (e) { console.log('外部捕获', e); } // 内部捕获 a // 外部捕获 b
上面代码中,遍历器对象i连续抛出两个错误。第一个错误被Generator函数体内的catch语句捕获。i第二次抛出错误,因为Generator函数内部的catch语句已经执行过了,不会再捕捉到这个错误了,因此这个错误就被抛出了Generator函数体,被函数体外的catch语句捕获。
注意,不要混淆遍历器对象的throw方法和全局的throw命令。上面代码的错误,是用遍历器对象的throw方法抛出的,而不是用throw命令抛出的。后者只能被函数体外的catch语句捕获
var g = function* () { while (true) { try { yield; } catch (e) { if (e != 'a') throw e; console.log('内部捕获', e); } } }; var i = g(); i.next(); try { throw new Error('a'); throw new Error('b'); } catch (e) { console.log('外部捕获', e); } // 外部捕获 [Error: a]
上面代码之因此只捕获了a,是由于函数体外的catch语句块,捕获了抛出的a错误之后,就不会再继续try代码块里面剩余的语句了。
若是 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函数g内部没有部署try...catch代码块,因此抛出的错误直接被外部catch代码块捕获。
若是 Generator 函数内部和外部,都没有部署try...catch代码块,那么程序将报错,直接中断执行:
var gen = function* gen(){ yield console.log('hello'); yield console.log('world'); } var g = gen(); g.next(); g.throw(); // hello // Uncaught undefined
上面代码中,g.throw抛出错误之后,没有任何try...catch代码块能够捕获这个错误,致使程序报错,中断执行。
throw方法被捕获之后,会附带执行下一条yield表达式。也就是说,会附带执行一次next方法:
var gen = function* gen(){ try { yield console.log('a'); } catch (e) { console.log('error'); } yield console.log('b'); yield console.log('c'); } var g = gen(); g.next() // a g.throw() // error,b g.next() // c
上面代码中,g.throw方法被捕获之后,自动执行了一次next方法,因此会打印b。另外,也能够看到,只要 Generator函数内部部署了try...catch代码块,那么遍历器的throw方法抛出的错误,不影响下一次遍历。
这种函数体内捕获错误的机制,大大方便了对错误的处理。多个yield表达式,能够只用一个try...catch代码块来捕获错误。若是使用回调函数的写法,想要捕获多个错误,就不得不为每一个函数内部写一个错误处理语句,如今只在 Generator 函数内部写一次catch语句就能够了。
Generator 函数体外抛出的错误,能够在函数体内捕获;反过来,Generator 函数体内抛出的错误,也能够被函数体外的catch捕获:
function* foo() { var x = yield 3; var y = x.toUpperCase(); yield y; } var it = foo(); it.next(); // { value:3, done:false } try { it.next(42); } catch (err) { console.log(err); }
上面代码中,第二个next方法向函数体内传入一个参数42,数值是没有toUpperCase方法的,因此会抛出一个 TypeError 错误,被函数体外的catch捕获。
一旦 Generator 执行过程当中抛出错误,且没有被内部捕获,就不会再执行下去了。若是此后还调用next方法,将返回一个value属性等于undefined、done属性等于true的对象,即 JavaScript 引擎认为这个 Generator 已经运行结束了:
function* g() { yield 1; console.log('throwing an exception'); throw new Error('generator broke!'); yield 2; yield 3; } function log(generator) { var v; console.log('starting generator'); try { v = generator.next(); console.log('第一次运行next方法', v); } catch (err) { console.log('捕捉错误', v); } try { v = generator.next(); console.log('第二次运行next方法', v); } catch (err) { console.log('捕捉错误', v); } try { v = generator.next(); console.log('第三次运行next方法', v); } catch (err) { console.log('捕捉错误', v); } console.log('caller done'); } log(g()); // starting generator // 第一次运行next方法 { value: 1, done: false } // throwing an exception // 捕捉错误 { value: 1, done: false } // 第三次运行next方法 { value: undefined, done: true } // caller done
上面代码一共三次运行next方法,第二次运行的时候会抛出错误,而后第三次运行的时候,Generator 函数就已经结束了,再也不执行下去了。
Generator 函数返回的遍历器对象,还有一个return方法,能够返回给定的值,而且终结遍历 Generator 函数:
function* gen() { yield 1; yield 2; yield 3; } var g = gen(); g.next() // { value: 1, done: false } g.return('foo') // { value: "foo", done: true } g.next() // { value: undefined, done: true }
上面代码中,遍历器对象g调用return方法后,返回值的value属性就是return方法的参数foo。而且,Generator函数的遍历就终止了,返回值的done属性为true,之后再调用next方法,done属性老是返回true。
若是return方法调用时,不提供参数,则返回值的value属性为undefined。
若是 Generator 函数内部有try...finally代码块,那么return方法会推迟到finally代码块执行完再执行:
function* numbers () { yield 1; try { yield 2; yield 3; } finally { yield 4; yield 5; } yield 6; } var g = numbers(); g.next() // { value: 1, done: false } g.next() // { value: 2, done: false } g.return(7) // { value: 4, done: false } g.next() // { value: 5, done: false } g.next() // { value: 7, done: true }
next()、throw()、return()这三个方法本质上是同一件事,能够放在一块儿理解。它们的做用都是让 Generator 函数恢复执行,而且使用不一样的语句替换yield表达式
next()是将yield表达式替换成一个值:
const g = function* (x, y) { let result = yield x + y; return result; }; const gen = g(1, 2); gen.next(); // Object {value: 3, done: false} gen.next(1); // Object {value: 1, done: true} // 至关于将 let result = yield x + y // 替换成 let result = 1;
throw()是将yield表达式替换成一个throw语句:
gen.throw(new Error('出错了')); // Uncaught Error: 出错了 // 至关于将 let result = yield x + y // 替换成 let result = throw(new Error('出错了'));
return()是将yield表达式替换成一个return语句:
gen.return(2); // Object {value: 2, done: true} // 至关于将 let result = yield x + y // 替换成 let result = return 2;
若是在 Generator 函数内部,调用另外一个 Generator 函数,默认状况下是没有效果的:
function* foo() { yield 'a'; yield 'b'; } function* bar() { yield 'x'; foo(); yield 'y'; } for (let v of bar()){ console.log(v); } // "x" // "y"
上面代码中,foo和bar都是 Generator 函数,在bar里面调用foo,是不会有效果的。
yield*表达式,用来在一个 Generator 函数里面执行另外一个 Generator 函数:
function* bar() { yield 'x'; yield* foo(); yield 'y'; } // 等同于 function* bar() { yield 'x'; yield 'a'; yield 'b'; yield 'y'; } // 等同于 function* bar() { yield 'x'; for (let v of foo()) { yield v; } yield 'y'; } for (let v of bar()){ console.log(v); } // "x" // "a" // "b" // "y"
再来看一个对比的例子:
function* inner() { yield 'hello!'; } function* outer1() { yield 'open'; yield inner(); yield 'close'; } var gen = outer1() gen.next().value // "open" gen.next().value // 返回一个遍历器对象 gen.next().value // "close" function* outer2() { yield 'open' yield* inner() yield 'close' } var gen = outer2() gen.next().value // "open" gen.next().value // "hello!" gen.next().value // "close"
上面例子中,outer2使用了yield*,outer1没使用。结果就是,outer1返回一个遍历器对象,outer2返回该遍历器对象的内部值。
从语法角度看,若是yield表达式后面跟的是一个遍历器对象,须要在yield表达式后面加上星号,代表它返回的是一个遍历器对象。这被称为yield*表达式。
yield*后面的 Generator 函数(没有return语句时),等同于在 Generator 函数内部,部署一个for...of循环:
function* concat(iter1, iter2) { yield* iter1; yield* iter2; } // 等同于 function* concat(iter1, iter2) { for (var value of iter1) { yield value; } for (var value of iter2) { yield value; } }
上面代码说明,yield-后面的Generator函数(没有return语句时),不过是for...of的一种简写形式,彻底能够用后者替代前者。反之,在有return语句时,则须要用var value = yield iterator的形式获取return语句的值:
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}
实际上,任何数据结构只要有 Iterator 接口,就能够被yield*遍历:
let read = (function* () { yield 'hello'; yield* 'hello'; })(); read.next().value // "hello" read.next().value // "h"
yield*命令能够很方便地取出嵌套数组的全部成员:
function* iterTree(tree) { if (Array.isArray(tree)) { for(let i=0; i < tree.length; i++) { yield* iterTree(tree[i]); } } else { yield tree; } } const tree = [ 'a', ['b', 'c'], ['d', 'e'] ]; for(let x of iterTree(tree)) { console.log(x); } // a // b // c // d // e
若是一个对象的属性是 Generator 函数,能够简写成下面的形式:
let obj = { * myGeneratorMethod() { ··· } }; //等价于 let obj = { myGeneratorMethod: function* () { // ··· } };
Generator 函数老是返回一个遍历器,ES6 规定这个遍历器是 Generator 函数的实例,也继承了 Generator 函数的prototype对象上的方法:
function* g() {} g.prototype.hello = function () { return 'hi!'; }; let obj = g(); obj instanceof g // true obj.hello() // 'hi!'
上面代码代表,Generator 函数g返回的遍历器obj,是g的实例,并且继承了g.prototype。可是,若是把g看成普通的构造函数,并不会生效,由于g返回的老是遍历器对象,而不是this对象。
function* g() { this.a = 11; } let obj = g(); obj.a // undefined
上面代码中,Generator函数g在this对象上面添加了一个属性a,可是obj对象拿不到这个属性。
Generator函数也不能跟new命令一块儿用,会报错:
function* g() { this.a = 11; } let obj = g(); obj.a // undefined
上面代码中,new命令跟构造函数F一块儿使用,结果报错,由于F不是构造函数。
那么,有没有办法让 Generator 函数返回一个正常的对象实例,既能够用next方法,又能够得到正常的this?
下面是一个变通方法。首先,生成一个空对象,使用call方法绑定Generator函数内部的this。这样,构造函数调用之后,这个空对象就是 Generator 函数的实例对象了:
function* F() { this.a = 1; yield this.b = 2; yield this.c = 3; } var obj = {}; var f = F.call(obj); f.next(); // Object {value: 2, done: false} f.next(); // Object {value: 3, done: false} f.next(); // Object {value: undefined, done: true} obj.a // 1 obj.b // 2 obj.c // 3
上面代码中,首先是F内部的this对象绑定obj对象,而后调用它,返回一个 Iterator 对象。这个对象执行三次next方法(由于F内部有两个yield表达式),完成F内部全部代码的运行。这时,全部内部属性都绑定在obj对象上了,所以obj对象也就成了F的实例。
上面代码中,执行的是遍历器对象f,可是生成的对象实例是obj,有没有办法将这两个对象统一呢?
一个办法就是将obj换成F.prototype:
function* F() { this.a = 1; yield this.b = 2; yield this.c = 3; } var f = F.call(F.prototype); f.next(); // Object {value: 2, done: false} f.next(); // Object {value: 3, done: false} f.next(); // Object {value: undefined, done: true} f.a // 1 f.b // 2 f.c // 3
再将F改为构造函数,就能够对它执行new命令了:
function* gen() { this.a = 1; yield this.b = 2; yield this.c = 3; } function F() { return gen.call(gen.prototype); } var f = new F(); f.next(); // Object {value: 2, done: false} f.next(); // Object {value: 3, done: false} f.next(); // Object {value: undefined, done: true} f.a // 1 f.b // 2 f.c // 3
Ajax 是典型的异步操做,经过 Generator 函数部署 Ajax 操做,能够用同步的方式表达:
function* main() { var result = yield request("http://some.url"); var resp = JSON.parse(result); console.log(resp.value); } function request(url) { makeAjaxCall(url, function(response){ it.next(response); }); } var it = main(); it.next();
上面代码的main函数,就是经过Ajax操做获取数据。能够看到,除了多了一个yield,它几乎与同步操做的写法彻底同样。注意,makeAjaxCall函数中的next方法,必须加上response参数,由于yield表达式,自己是没有值的,老是等于undefined。
若是有一个多步操做很是耗时,采用回调函数,可能会写成下面这样:
step1(function (value1) { step2(value1, function(value2) { step3(value2, function(value3) { step4(value3, function(value4) { // Do something with value4 }); }); }); });
采用 Promise 改写上面的代码:
Promise.resolve(step1) .then(step2) .then(step3) .then(step4) .then(function (value4) { // Do something with value4 }, function (error) { // Handle any error from step1 through step4 }) .done();
Generator 函数能够进一步改善代码运行流程:
function* longRunningTask(value1) { try { var value2 = yield step1(value1); var value3 = yield step2(value2); var value4 = yield step3(value3); var value5 = yield step4(value4); // Do something with value4 } catch (e) { // Handle any error from step1 through step4 } }
而后,使用一个函数,按次序自动执行全部步骤:
scheduler(longRunningTask(initialValue)); function scheduler(task) { var taskObj = task.next(task.value); // 若是Generator函数未结束,就继续调用 if (!taskObj.done) { task.value = taskObj.value scheduler(task); } }
注意,上面这种作法,只适合同步操做,即全部的task都必须是同步的,不能有异步操做。由于这里的代码一获得返回值,就继续往下执行,没有判断异步操做什么时候完成
Generator 是实现状态机的最佳结构。好比,下面的clock函数就是一个状态机:
var ticking = true; var clock = function() { if (ticking) console.log('Tick!'); else console.log('Tock!'); ticking = !ticking; }
上面代码的clock函数一共有两种状态(Tick和Tock),每运行一次,就改变一次状态。这个函数若是用 Generator 实现,就是下面这样:
var clock = function* () { while (true) { console.log('Tick!'); yield; console.log('Tock!'); yield; } };
上面的 Generator 实现与 ES5 实现对比,能够看到少了用来保存状态的外部变量ticking,这样就更简洁,更安全(状态不会被非法篡改)、更符合函数式编程的思想,在写法上也更优雅。Generator之因此能够不用外部变量保存状态,是由于它自己就包含了一个状态信息,即目前是否处于暂停态。
利用 Generator 函数,能够在任意对象上部署 Iterator 接口:
function* iterEntries(obj) { let keys = Object.keys(obj); for (let i=0; i < keys.length; i++) { let key = keys[i]; yield [key, obj[key]]; } } let myObj = { foo: 3, bar: 7 }; for (let [key, value] of iterEntries(myObj)) { console.log(key, value); } // foo 3 // bar 7
上述代码中,myObj是一个普通对象,经过iterEntries函数,就有了Iterator接口。也就是说,能够在任意对象上部署next方法。