zoukankan      html  css  js  c++  java
  • ES6-----学习系列十六(Generator)

    Generator可以理解为异步编程的一种解决方案。

      1、generator的基本定义就是在function后面加一个*符号  通过next一步步执行yield的代码

    {
      // genertaor基本定义
      let tell=function* (){
        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 value of obj){
        console.log('value',value);
      }
    }

    来一个具体事例吧,这个确实理解不是很深

      1、抽奖

    {
      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)
    }

      2、长轮询  

    {
      // 长轮询
      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();
    }
  • 相关阅读:
    今天还要去一次北仑
    重归漫漫长路
    双休日,累
    调整心情,迎接新的挑战
    多喝点水,对身体有好处
    丈人生病住院了
    WPF,DataGrid数据绑定
    AXIS2简介
    心事一件件的了掉,希望一切都能恢复到正常
    驾车是种乐趣,也是种累
  • 原文地址:https://www.cnblogs.com/diasa-fly/p/7026122.html
Copyright © 2011-2022 走看看