Web端 es6(基础十四) genertaor

时间:2021-05-02 23:31:25

基本使用

let tell = function* () {
yield 'A';
yield 'B';
yield 'C';
};
let k = tell();
console.log(k.next());
console.log(k.next());
console.log(k.next());
console.log(k.next());
// 输出结果
{value: "A", done: false}
{value: "B", done: false}
{value: "C", done: false}
{value: undefined, done: true}

与 iterator 结合使用

let obj = {};
obj[Symbol.iterator] = function* () {
yield 1;
yield 2;
yield 3;
};
for (let value of obj){
console.log('value',value)
}
// 输出结果
value 1
value 2
value 3

状态机

let status = function* () {
while (1){
yield 'A';
yield 'B';
yield 'C';
}
};
let state = status();
console.log(state.next());
console.log(state.next());
console.log(state.next());
console.log(state.next());
// 输出结果
{value: "A", done: false}
{value: "B", done: false}
{value: "C", done: false}
{value: "A", done: false}

抽奖逻辑

let  draw = function (count) {
console.log(`剩余抽奖次数 -> ${count}`);
};

let residue = function *(count) {
while (count > 0){
count--;
yield draw(count);
}
console.log("没有多余的抽奖机会了")
};
let start = residue(5);
start.next();
start.next();
start.next();
start.next();
start.next();
start.next();
// 输出结果
剩余抽奖次数 -> 4
剩余抽奖次数 -> 3
剩余抽奖次数 -> 2
剩余抽奖次数 -> 1
剩余抽奖次数 -> 0
没有多余的抽奖机会了

长轮训

// 长轮询
let ajax = function* () {
yield new Promise(function (resolve, reject) {
setTimeout(function () {
console.log('拿到数据了...');
resolve({code:0})
},200)
})
};
let pull = function () {
let genertator = ajax();
let step = genertator.next();
step.value.then(function (data) {
//重试
setTimeout(function () {
console.log('wait');
pull()
},1000)
})
};
//开始轮询
pull();