es6 语法金沙官网线上 (Generator)

{
  // 长轮询
  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){//step.value就是promise实例
      if(d.code!=0){
        setTimeout(function () {
          console.info('wait');
          pull()
        }, 1000);
      }else{
        console.info(d);
      }
    })
  }

  pull();
}

金沙官网线上, 

Generator 函数是协程在 ES6 的实现,最大特点就是可以交出函数的执行权(即暂停执行)
参考链接:
http://www.ruanyifeng.com/blog/2015/04/generator.html
{
    // genertaor基本定义 有一个星号有一个yield
    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: false}
    console.log(k.next()); // {value: undefined, done: true}
}

{
    let obj = {};
    obj[Symbol.iterator] = function*() {
        yield 1;
        yield 2;
        yield 3;
    }

    for (let value of obj) {
        console.log('value', value); // 1 2 3
    }
}

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

// {
//需要一些插件才能实现,结果跟上面一样
//   let state=async function (){
//     while(1){
//       await 'A';
//       await 'B';
//       await 'C';
//     }
//   }
//   let status=state();
//   console.log(status.next());
//   console.log(status.next());
//   console.log(status.next());
//   console.log(status.next());
//   console.log(status.next());
// }

{
    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 = 'start';
    btn.textContent = '抽奖';
    document.body.appendChild(btn);
    document.getElementById('start').addEventListener('click', function() {
        star.next();
    }, false)
}

 

本文由金沙官网线上发布于Web前端,转载请注明出处:es6 语法金沙官网线上 (Generator)

您可能还会对下面的文章感兴趣: