generator
Posted wangshouren
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了generator相关的知识,希望对你有一定的参考价值。
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);
})
以上是关于generator的主要内容,如果未能解决你的问题,请参考以下文章
[React Testing] Use Generated Data in Tests with tests-data-bot to Improve Test Maintainability(代码片段
Xcode8:"subsystem: com.apple.UIKit, category: HIDEventFiltered, enable_level: 0" 的警告(代码片段