generator
生成器,生成迭代器的,es6语法。迭代器有next方法,方法执行后需要返回value,done
1.用法
//返回值叫迭代器,迭代器有next方法,方法执行后需要返回value,done。
function * read(){
yield 1;//产出,每次遇到yield停住
yield 2;
yield 3;
}
let it=read();
console.log(it.next());//{value:1,done:false}
console.log(it.next());
console.log(it.next());
console.log(it.next());//{value:undefined,done:true}
2. ...扩展类数组 和 for...of
原理就是调用 [Symbol.iterator] 生成迭代器
let obj = {
0: 1,
1: 2,
length: 2,
[Symbol.iterator]: function * () {
let index=0;
while(index!=this.length){
yield this[index++];
}
}
}
console.log(...obj);//1,2
3.async+await原理
//实现函数co
//name.txt:age.txt
//age.txt:10
const fs = require('fs').promises;
function* read() {
let content = yield fs.readFile(__dirname+'/name.txt', 'utf8');
let age = yield fs.readFile(__dirname+'/'+content, 'utf8');
return age;
}
co(read()).then(res => console.log(res))//10
//co
let co = (it) => new Promise((resolve, reject) => {
let next = (v) => {
let { value, done } = it.next(v);
return done ? resolve(value) : Promise.resolve(value).then(next, reject);
}
next(undefined);
})