Generator异步处理
{ // genertaor基本定义,next()一步步执行 let tell=function* (){ yield 'a'; yield 'b'; return 'c' }; let k=tell(); console.log(k.next()); //{value: "a", done: false} console.log(k.next()); //{value: "b", done: false} console.log(k.next()); //{value: "c", done: true} console.log(k.next());//{value: undefined, done: true} }
应用场景
// 应用场景,变量变化的实时存储 { let draw=function(count){ // 具体抽奖逻辑 console.info(`剩余${count}次`) } let residue=function *(count){ while(count>0){ count--; yield draw(count); } } let star=residue(5); let btn=document.createElement("button"); btn.id='star'; btn.textContent='抽奖'; document.body.appendChild(btn); document.getElementById('star').addEventListener("click",function(){ star.next(); },false) }
长轮询(服务端某个状态在变化,我们也需要实时去访问变化)
{ // 长轮询(服务端某个状态在变化,我们也需要实时去访问变化) let ajax=function* (){ yield new Promise(function(resolve,reject){ setTimeout(function(){ resolve({code:1}) },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.log(d); } }) } pull(); }
Decorator函数修饰符,通过修饰器修改类的行为