generator和...

//generator 生成器 =》遍历器(需要有一个next方法)=》数组=》类数组
//...原理就是遍历这个对象,将结果放到数组中,这个数据必须得有个遍历器。[...new Set()] for  of
//[...likeArray] /Array.from(likeArray)
const likeArray = { 0: "a", 1: "b", 2: "c", 3: "d", length: 4 };
//Symbol.iterator就是一个属性,给当前对象添加遍历器,这是数组必须的属性
likeArray[Symbol.iterator] = function () {
  let i = 0;
  return {
    next: () => {
      return { value: this[i], done: i++ === this.length };
    },
  };
};
//上面的和下面的一致,这是”元“编程 自己改写js原有的功能
likeArray[Symbol.iterator] = function* () {
  let i = 0;
  while (i !== this.length) {
    yield this[i++];
  }
};
// generator 生成器 生成的是迭代器
// 普通函数执行时 没有停止功能,generator函数 可以暂停
function * read() {
    yield 1; // 产出
    yield 2; // 产出
    yield 3; // 产出
    yield 4; // 产出
}

let it = read(); // iterator 迭代器中包含一个next方法

// 迭代器接口 Symbol.iterator
let done = false;
while(!done){
    let obj  =  it.next();
    done = obj.done;
    console.log(obj.value);
}
console.log(it.next()); // {value,done} 配到yield关键字就停止了
console.log(it.next()); 



// ---------------
// es6特性
function * read() {
    let a = yield 1;
    console.log('a'+a);
    let b = yield 2; 
    console.log('b'+b);
    let c = yield 3;
    console.log(c); 
}
let it = read();

it.next('xxx'); // 第一次传递的参数 是无意义的
it.next('world'); // next传递参数会给上一次yield的返回值
it.next('xxx');

// generator + promise
const util = require('util');
const fs = require('fs');
let read = util.promisify(fs.readFile);
function * readAge(){ // 暂停的功能
    let content =  yield read('./name.txt','utf8');
    let age = yield {}
    return age;
}
原文地址:https://www.cnblogs.com/TTblog5/p/13081079.html