Class // Array Generator
// array of classes generator function FNS () { the let obj = {0: 1,1: 2,2 &:. 3, length:. 3}, [Symbol.iterator]: function () { the let index = 0; the let that the this =; return { Next () { return { value: that [index], DONE: === that.length index ++ } } } } the let ARR = [... obj]; the console.log (Array.isArray (ARR ), ARR); } // automate Next function FNS () { // add the iterative approach to array- let obj = {0: 1,1: 2,2: 3, length: 3}, [Symbol.iterator] : function () { the let index = 0; the let = that the this; the while (index === that.length) { the yield that [index ++] } } let arr = [...obj]; console.log(Array.isArray(arr), arr); } fns(1,2,3,4,5)
#### co Module
// generator + promise 来使用 let fs = require('fs').promises; // promise 要通过then generator 可以省略then方法 function* read() { // try{ let content = yield fs.readFile('./name.txt','utf8'); let age = yield fs.readFile(content,'utf8'); let a = yield age + 100; return a; // }catch(err){ // console.log(err); // } } // co 库 function co(it){ return new Promise((resolve,reject)=>{ // 异步迭代 next function next(data){ let {value,done} = it.next(data); if(!done){ Promise.resolve(value).then(data=>{ next(data) },reject); }else{ resolve(value); } } next(); }); } co(read()).then(data=>{ console.log(data); });
#### for the first time next invalid, and to stop the local yield. next to where the value is copied to the copy of the value of yield.