实例:
1.前端实现抽奖次数的限制。
{
let draw = function (count) {
// 具体抽奖业务逻辑
console.log(`剩余${count}次`);
}
let residue = function* (count){
while(count > 0){
count--;
yield draw(count);
}
}
let star = residue(5); //5为后台传输进来的抽奖次数
let btn = document.createElement('button');
btn.id = 'start';
btn.textContent = '抽奖';
document.body.appendChild(btn);
document.getElementById('start').addEventListener('click',function(){
star.next();
},false);
}
2.长轮询
{
let ajax = function* (){ //接口模拟
yield new Promise(function(resolve,reject){
setTimeout(function(){ //此处为项目中正常的请求数据逻辑
resolve({code: 0});
},200)
})
}
let pull = function(){ //此段可以直接用,只需修改上方接口逻辑
let generator = ajax();
let step = generator.next();
step.value.then(function(d){
if (d.code != 0) {
setTimeout(function(){
console.log('wait');
pull();
},1000);
}else{
console.log(d);
}
})
}
pull();
}
网友评论