Iterator
已经部署Iterator接口的数据
array、map、set、string、TypeArray、NodeList、arguments
obj添加遍历起
let obj={
a:1,
b:2,
c:3,
[Symbol.iterator](){
let nextIndex=0;
let map=new Map();
for(let [key,value] of Object.entries(this)) {
map.set(key,value)
}
let mapEnteries=[...map.entries()];
return {
next(){
return nextIndex<mapEnteries.length?
{value: mapEnteries[nextIndex++],done: false}:{
value: undefined,done: true
}
}
}
}
}
for(let i of obj){
console.log(i)
}
使用generator函数
let obj={
a:0,
b:9,
[Symbol.iterator]: function *(){
let nextIndex=0;
let map=new Map();
for(let [key,value] of Object.entries(this)) {
map.set(key,value)
}
let mapEnteries=[...map.entries()];
while(nextIndex<len){
yield arr[nextIndex++]
}
}
}
Generator
generator也是迭代器可以用for…of遍历
function * foo(){
let value1=yield 1;
console.log(value1); //two
let value2=yield 2;
let value3=yield 3;
}
let iter=foo();
iter.next('one')
iter.next('two')
let fs=require('fs');
fs.readFile('./name.txt','utf-8',(err,data)=>{
fs.readFile(data,'utf-8',(err,data)=>{
fs.readFile(data,'utf-8',(err,data)=>{
console.log(data)
})
})
})
function promisify(fn) {
return function(...args) {
return new Promise((resolve,reject)=>{
fn(...args,(err,data)=>{
if(err){
reject(err);
}else{
resolve(data)
}
})
})
}
}
let readFile=promisify(fs.readFile);
readFile('./name.txt','uft-8')
.then(res=>readFile(res,'utf-8'))
.then(res=>readFile(res,'utf-8'))
.then(res=>console.log(res))
function * read() {
let value1=yield readFile('./name.txt','utf-8');
let value2=yield readFile(value1,'utf-8');
let value3=yield readFile(value2,'utf-8');
console.log(value3)
}
let iter=read();
let {value,done}=iter.next();
value.then((val1)=>{
let {value,done}=iter.next(val1);
value.then((val2)=>{
let {value,done}=iter.next(val2);
value.then((val3)=>{
console.log('val3',val3)
})
})
})
优化:
function Co(iter) {
return new Promise((resolve,reject)=>{
let next=(data)=>{
let {value,done}=iter.next(data);
if(done) {
resolve(value);
}else{
value.then((val)=>{
next(val)
})
}
next();
}
})
}
let promise=Co(read());
promise.then((val)=>{
console.log(val);
})