1. 程式人生 > >ES6學習筆記七Generator、Decorators

ES6學習筆記七Generator、Decorators

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函式修飾符,通過修飾器修改類的行為