理解Generator生成器对象

Generator 对象(理解为生成器函数更好)

  • 注意,Generator函数,不可当作构造函数
  • 首先声明一个Generator 函数,以下均以 gen 为例
function* gen(){
  yield "first";
  yield "second";
  yield "third";
}
var res = gen();
  • 它是一个高阶函数(gen),可以生成一个可迭代的函数(res)
  • 生成的函数(res),是一个惰性函数,每次迭代都重写自身
  • 惰性函数(res)有一个next方法,可以执行链式调用

function*语法糖

  • 它以这种方式,规定了Generator继承自GeneratorFunction
  • 如下,可以看到,gen的构造器属性为GeneratorFunction
  • 不出意外,GeneratorFunction的构造器属性则是Function
gen.constructor;//ƒ GeneratorFunction() { [native code] };
gen.constructor.constructor;//ƒ Function() { [native code] };

GeneratorFunction构造器

  • Generator 生成器函数是 GeneratorFunction 的实例对象
  • GeneratorFunction.constructor的初始值是 GeneratorFunction,且不可被修改
  • 但是,GeneratorFunction并不是一个全局对象。获取比较麻烦一点
Object.getPrototypeOf(function*(){}).constructor

用GeneratorFunction构造函数创建一个生成器函数

  • 需要显示调用 new 。最后一个参数为函数体,之前的都为函数的参数(注意均为字符串形式)
var GeneratorFunction = Object.getPrototypeOf(function*(){}).constructor
var gen = new GeneratorFunction("a","b", "yield a * b");
var iterator = gen(10,20);
console.log(iterator.next().value); // 200

Generator 对象(函数)的方法

  • next,是一个迭代器方法
  • 分析可知,next方法是 GeneratorFunction 对象的原型方法
gen.constructor.prototype
//GeneratorFunction{prototype: Generator, constructor: ƒ, Symbol(Symbol.toStringTag): "GeneratorFunction"}    
gen.constructor.prototype.prototype.next
//ƒ next() { [native code] }
  • return,结束迭代并且返回一个vaule值
console.log(res.next());//{ "value": "first", "done": false }
console.log(res.return("444"));//{ "value": "444", "done": true }
console.log(res.next());//{ "done": true },此时已经没有value值了
  • throw,异常抛出,内部通过 try…catch 块进行捕获
gen.throw(new Error("Something went wrong")); 

向 Generator 传递数据和传递参数

//传递数据
function* gem_1(){
  let color = yield;
  let name = yield;
  console.log(color,name);
}
const iterator_1 = gem_1();
console.log(iterator_1.next());//{ "done": false }
console.log(iterator_1.next("red"));//{ "done": false }
console.log(iterator_1.next("gs"));//red gs { "done": true }
//传递参数
function* gem_2(color,name){
  yield color;
  yield name;
}
const iterator_2 = gem_2("green","zk");
console.log(iterator_2.next());//{ "value": "green", "done": false }
console.log(iterator_2.next());//{ "value": "zk", "done": false }
console.log(iterator_2.next());//{ "done": true }

最终实现异步回调的同步处理

let iterator;//注意先声明iterator

const iterOne = () => {
  setTimeout(function() {
    iterator.next(111);
  }, 1000);
}
const iterTwo = () => {
  setTimeout(function() {
    iterator.next(222);
  }, 3000);
}

function* gen(){
  const one = yield iterOne();
  const two = yield iterTwo();
  console.log(one*2 + two);
}

iterator = gen();
iterator.next();//444

你可能感兴趣的:(javascript函数式编程,javascript函数式编程)