标签:generator == content java isa resolve 停止 info dex
// 类数组的生成器
// 类数组的生成器 function fns() { let obj = {0:1,1:2,2:3,length: 3}, [Symbol.iterator]: function() { let index = 0; let that = this; return { next() { return { value: that[index], done: index++ === that.length } } } } let arr = [...obj]; console.log(Array.isArray(arr), arr); } // 自动执行next function fns() { // 给类数组添加迭代方法 let obj = {0:1,1:2,2:3,length: 3}, [Symbol.iterator]: function() { let index = 0; let that = this; while(index === that.length) { yield that[index++] } } let arr = [...obj]; console.log(Array.isArray(arr), arr); } fns(1,2,3,4,5)
#### co模块
// 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); });
#### 第一次next无效,并且停止到yield的地方。next里的值会复制给yield复制给的值。
标签:generator == content java isa resolve 停止 info dex
原文地址:https://www.cnblogs.com/coding4/p/11520347.html