Generator

Generator

首先可以把它理解成,Generator 函数是一个状态机,封装了多个内部状态。Generator 函数除了状态机,还是一个遍历器对象生成函数。

Generator 函数有两个特征。一是,function关键字与函数名之间有一个星号;二是,函数体内部使用yield表达式,定义不同的内部状态.

	function* helloWorldGenerator() {
	  yield 'hello';
	  yield 'world';
	  return 'ending';
	}
	var hw = helloWorldGenerator();
	//函数有三个状态:hello,world 和 return 语句(结束执行)。
	//一个函数里面,只能执行一次(或者说一个)return语句,但是可以执行多次(或者说多个)yield表达式。

调用 Generator 函数后,该函数并不执行,返回的也不是函数运行结果,而是一个指向内部状态的指针对象
必须调用遍历器对象的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 函数可以不用yield表达式,这时就变成了一个单纯的暂缓执行函数。同时yield表达式只能用在 Generator 函数里面,用在其他地方都会报错。

	function* f() {
	  console.log('执行了!')
	}
	var generator = f();
	setTimeout(function () {
	  generator.next()
	}, 2000);

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
	}

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

Generator.prototype.throw()

Generator函数返回的遍历器对象,都有一个throw方法,可以在函数体外抛出错误,然后在Generator函数体内捕获。
throw方法抛出的错误要被内部捕获,前提是必须至少执行过一次next方法.

	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语句捕获。

如果 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代码块,那么程序将报错,直接中断执行。

	var gen = function* gen(){
	  yield console.log('hello');
	  yield console.log('world');
	}
	
	var g = gen();
	g.next();
	g.throw();
	// hello
	// Uncaught undefined

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。

如果 Generator 函数内部有try…finally代码块,且正在执行try代码块,那么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 }

上面代码中,调用return()方法后,就开始执行finally代码块,不执行try里面剩下的代码了,然后等到finally代码块执行完,再返回return()方法指定的返回值。

next()、throw()、return() 的共同点

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;

应用

异步任务的封装
	var fetch = require('node-fetch');
	
	function* gen(){
	  var url = 'https://api.github.com/users/github';
	  var result = yield fetch(url);
	  console.log(result.bio);
	}

Generator 函数封装了一个异步操作,该操作先读取一个远程接口,然后从 JSON 格式的数据解析信息。

执行上面的代码如下:

	var g = gen();
	var result = g.next();
	
	result.value.then(function(data){
	  return data.json();
	}).then(function(data){
	  g.next(data);
	});

上面代码中,首先执行 Generator 函数,获取遍历器对象,然后使用next方法(第二行),执行异步任务的第一阶段。由于Fetch模块返回的是一个 Promise 对象,因此要用then方法调用下一个next方法。

部署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方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值