博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ECMAScript6学习笔记-Generator
阅读量:2490 次
发布时间:2019-05-11

本文共 12198 字,大约阅读时间需要 40 分钟。

一、Generator函数概念

Generator 函数有多种理解角度。语法上,首先可以把它理解成,Generator 函数是一个状态机,封装了多个内部状态。

执行 Generator 函数会返回一个遍历器对象,也就是说,Generator 函数除了状态机,还是一个遍历器对象生成函数。返回的遍历器对象,可以依次遍历 Generator 函数内部的每一个状态。

形式上,Generator 函数是一个普通函数,但是有两个特征。一是,function关键字与函数名之间有一个星号;二是,函数体内部使用yield表达式,定义不同的内部状态(yield在英语里的意思就是“产出”)。

function* helloWorldGenerator() {
yield 'hello'; yield 'world'; return 'ending';}var hw = helloWorldGenerator();

上面代码定义了一个 Generator 函数helloWorldGenerator,它内部有两个yield表达式(hello和world),即该函数有三个状态:hello,world 和 return 语句(结束执行)。

Generator 函数的调用方法与普通函数一样,也是在函数名后面加上一对圆括号。不同的是,调用 Generator 函数后,该函数并不执行,返回的也不是函数运行结果,而是一个指向内部状态的指针对象,也就是上一章介绍的遍历器对象(Iterator Object)。

下一步,必须调用遍历器对象的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 }

调用 Generator 函数,返回一个遍历器对象,代表 Generator 函数的内部指针。以后,每次调用遍历器对象的next方法,就会返回一个有着value和done两个属性的对象。value属性表示当前的内部状态的值,是yield表达式后面那个表达式的值;done属性是一个布尔值,表示是否遍历结束。

二、yield表达式

由于 Generator 函数返回的遍历器对象,只有调用next方法才会遍历下一个内部状态,所以其实提供了一种可以暂停执行的函数。yield表达式就是暂停标志。

遍历器对象的next方法的运行逻辑如下。

(1)遇到yield表达式,就暂停执行后面的操作,并将紧跟在yield后面的那个表达式的值,作为返回的对象的value属性值。

(2)下一次调用next方法时,再继续往下执行,直到遇到下一个yield表达式。

(3)如果没有再遇到新的yield表达式,就一直运行到函数结束,直到return语句为止,并将return语句后面的表达式的值,作为返回的对象的value属性值。

(4)如果该函数没有return语句,则返回的对象的value属性值为undefined。

yield表达式后面的表达式,只有当调用next方法、内部指针指向该语句时才会执行

function* gen() {
yield 123 + 456;}//yield后面的表达式123 + 456,不会立即求值,只会在next方法将指针移到这一句时,才会求值。

Generator 函数可以不用yield表达式,这时就变成了一个单纯的暂缓执行函数。

function* f() {
console.log('执行了!')}var generator = f();setTimeout(function () {
generator.next()}, 2000);//函数f如果是普通函数,在为变量generator赋值时就会执行。但是,函数f是一个 Generator 函数,就变成只有调用next方法时,函数f才会执行。

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}

三、与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属性,执行后返回自身。

function* gen(){
// some code}var g = gen();g[Symbol.iterator]() === g

四、next方法的参数

yield表达式本身没有返回值,或者说总是返回undefined。next方法可以带一个参数,该参数就会被当作上一个yield表达式的返回值。

function* f() {  for(var i = 0; true; i++) {    var reset = yield i;    if(reset) { i = -1; }  }}var g = f();g.next() // { value: 0, done: false }g.next() // { value: 1, done: false }g.next(true) // { value: 0, done: false }//上面代码先定义了一个可以无限运行的 Generator 函数f,如果next方法没有参数,每次运行到yield表达式,变量reset的值总是undefined。当next方法带一个参数true时,变量reset就被重置为这个参数(即true),因此i会等于-1,下一轮循环就会从-1开始递增。

这个功能有很重要的语法意义。Generator 函数从暂停状态到恢复运行,它的上下文状态(context)是不变的。通过next方法的参数,就有办法在 Generator 函数开始运行之后,继续向函数体内部注入值。也就是说,可以在 Generator 函数运行的不同阶段,从外部向内部注入不同的值,从而调整函数行为。

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 }

上面代码中,第二次运行next方法的时候不带参数,导致 y 的值等于2 * undefined(即NaN),除以 3 以后还是NaN,因此返回对象的value属性也等于NaN。第三次运行Next方法的时候不带参数,所以z等于undefined,返回对象的value属性等于5 + NaN + undefined,即NaN。

如果向next方法提供参数,返回结果就完全不一样了。上面代码第一次调用b的next方法时,返回x+1的值6;第二次调用next方法,将上一次yield表达式的值设为12,因此y等于24,返回y / 3的值8;第三次调用next方法,将上一次yield表达式的值设为13,因此z等于13,这时x等于5,y等于24,所以return语句的值等于42。

注意,由于next方法的参数表示上一个yield表达式的返回值,所以在第一次使用next方法时,传递参数是无效的。V8 引擎直接忽略第一次使用next方法时的参数,只有从第二次使用next方法开始,参数才是有效的。从语义上讲,第一个next方法用来启动遍历器对象,所以不用带有参数。

五、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

上面代码使用for…of循环,依次显示 5 个yield表达式的值。这里需要注意,一旦next方法的返回对象的done属性为true,for…of循环就会中止,且不包含该返回对象,所以上面代码的return语句返回的6,不包括在for…of循环之中。

利用for…of循环,可以写出遍历任意对象(object)的方法。原生的 JavaScript 对象没有遍历接口,无法使用for…of循环,通过 Generator 函数为它加上这个接口,就可以用了。

function* objectEntries(obj) {
let propKeys = Reflect.ownKeys(obj); for (let propKey of propKeys) { yield [propKey, obj[propKey]]; }}let jane = { first: 'Jane', last: 'Doe' };for (let [key, value] of objectEntries(jane)) { console.log(`${key}: ${value}`);}// first: Jane// last: Doe

上面代码中,对象jane原生不具备 Iterator 接口,无法用for…of遍历。这时,我们通过 Generator 函数objectEntries为它加上遍历器接口,就可以用for…of遍历了。加上遍历器接口的另一种写法是,将 Generator 函数加到对象的Symbol.iterator属性上面。

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

六、Generator.prototype.throw()

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

上面代码中,遍历器对象i连续抛出两个错误。第一个错误被 Generator 函数体内的catch语句捕获。i第二次抛出错误,由于 Generator 函数内部的catch语句已经执行过了,不会再捕捉到这个错误了,所以这个错误就被抛出了 Generator 函数体,被函数体外的catch语句捕获。

throw方法可以接受一个参数,该参数会被catch语句接收,建议抛出Error对象的实例。

var g = function* () {
try { yield; } catch (e) { console.log(e); }};var i = g();i.next();i.throw(new Error('出错了!'));// Error: 出错了!(…)

不要混淆遍历器对象的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);}

如果 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

throw方法被捕获以后,会附带执行下一条yield表达式。也就是说,会附带执行一次next方法

var gen = function* gen(){
try { yield console.log('a'); } catch (e) { // ... } yield console.log('b'); yield console.log('c');}var g = gen();g.next() // ag.throw() // bg.next() // c

这种函数体内捕获错误的机制,大大方便了对错误的处理。多个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);}

一旦 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

七、Generator.prototype.return()

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。

function* gen() {
yield 1; yield 2; yield 3;}var g = gen();g.next() // { value: 1, done: false }g.return() // { value: undefined, done: true }

如果 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 }

八、yield*表达式

如果在 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"

从语法角度看,如果yield表达式后面跟的是一个遍历器对象,需要在yield表达式后面加上星号,表明它返回的是一个遍历器对象。这被称为yield*表达式。

let delegatedIterator = (function* () {
yield 'Hello!'; yield 'Bye!';}());let delegatingIterator = (function* () {
yield 'Greetings!'; yield* delegatedIterator; yield 'Ok, bye.';}());for(let value of delegatingIterator) { console.log(value);}// "Greetings!// "Hello!"// "Bye!"// "Ok, bye."

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*后面跟着一个数组,由于数组原生支持遍历器,因此就会遍历数组成员。

function* gen(){  yield* ["a", "b", "c"];}gen().next() // { value:"a", done:false }

上面代码中,yield命令后面如果不加星号,返回的是整个数组,加了星号就表示返回的是数组的遍历器对象。

实际上,任何数据结构只要有 Iterator 接口,就可以被yield*遍历。

let read = (function* () {
yield 'hello'; yield* 'hello';})();read.next().value // "hello"read.next().value // "h"

如果被代理的 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 函数

如果一个对象的属性是 Generator 函数,可以简写成下面的形式。

let obj = {  * myGeneratorMethod() {    ···  }};let obj = {  myGeneratorMethod: function* () {
// ··· }};

十、Generator 函数的this

Generator 函数总是返回一个遍历器,ES6 规定这个遍历器是 Generator 函数的实例,也继承了 Generator 函数的prototype对象上的方法。

function* g() {
}g.prototype.hello = function () {
return 'hi!';};let obj = g();obj instanceof g // trueobj.hello() // 'hi!'

上面代码表明,Generator 函数g返回的遍历器obj,是g的实例,而且继承了g.prototype。但是,如果把g当作普通的构造函数,并不会生效,因为g返回的总是遍历器对象,而不是this对象。

function* g() {
this.a = 11;}let obj = g();obj.next();obj.a // undefined

上面代码中,Generator 函数g在this对象上面添加了一个属性a,但是obj对象拿不到这个属性。

Generator 函数也不能跟new命令一起用,会报错。

function* F() {  yield this.x = 2;  yield this.y = 3;}new F()// TypeError: F is not a constructor

参考:

转载地址:http://erarb.baihongyu.com/

你可能感兴趣的文章
VNPY - 事件引擎
查看>>
MongoDB基本语法和操作入门
查看>>
学习笔记_vnpy实战培训day04_作业
查看>>
OCO订单(委托)
查看>>
学习笔记_vnpy实战培训day06
查看>>
回测引擎代码分析流程图
查看>>
Excel 如何制作时间轴
查看>>
股票网格交易策略
查看>>
matplotlib绘图跳过时间段的处理方案
查看>>
vnpy学习_04回测评价指标的缺陷
查看>>
ubuntu终端一次多条命令方法和区别
查看>>
python之偏函数
查看>>
vnpy学习_06回测结果可视化改进
查看>>
读书笔记_量化交易如何建立自己的算法交易01
查看>>
设计模式03_工厂
查看>>
设计模式04_抽象工厂
查看>>
设计模式05_单例
查看>>
设计模式06_原型
查看>>
设计模式07_建造者
查看>>
设计模式08_适配器
查看>>