//generator
//基本用法 { // generator function* tell(){ yield 'a'; yield 'b'; return 'c' }; let k=tell(); console.log(k.next()); console.log(k.next()); console.log(k.next()); console.log(k.next()); } //应用 { let obj={}; obj[Symbol.iterator]=function *(){ yield 1; yield 2; yield 3; } for(let item of obj){ console.log(item) } }
//实例
//实例 let draw=function(count){ //具体抽奖逻辑 console.log(`剩余${count}次`); }; let residue=function* (count){ while(count>0){ count--; yield draw(count); } }; let start=residue(5); let btn=document.createElement("button"); btn.id="start"; btn.textContent="抽奖"; document.body.appendChild(btn); console.log(2222222222222); document.getElementById("start").addEventListener("click",function(){ start.next(); },false);
长轮循
//长轮循 //连续请求服务端接口,当服务端返回为0时,停止查询 let ajax=function* (){ yield new Promise(function(resolve, reject){ //请求服务端的数据 setTimeout(function(){ resolve({code:0}) },200) }) } let pull=function(){ let genertaor=ajax(); let step=genertaor.next(); step.value.then(function(d){ if(d.code!=0){ setTimeout(function(){ console.info("wait"); pull(); },1000) }else{ console.info(d); } }) } pull();