zoukankan      html  css  js  c++  java
  • ES6 Generator的应用场景

    一、基础知识

    API文档

    ES6 诞生以前,异步编程的方法,大概有下面四种。

    • 回调函数
    • 事件监听
    • 发布/订阅
    • Promise 对象

    Generator 函数将 JavaScript 异步编程带入了一个全新的阶段。

    二、应用场景

    1.比如抽奖环节,当前用户还可以抽奖5次。点击后次数减1。

    若采用ES5的方式,不使用Generator,则需要将count存入全局变量中,但是这样非常不安全,如果别人知道变量是什么,就可以修改变量;另外存入全局变量也会影响性能。

    {
        let draw=function(count){
            //具体抽奖逻辑,跟次数的校验是分开的
            //输出剩余次数
            console.log(`剩余${count}次`)
        }
       //利用Generator控制次数
        let residue=function*(count){
            while(count>0){
                count--
                yield draw(count)
            }
        }
      //将Generator实例化,通过按钮绑定,点击执行next,进行抽奖
        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.长轮询

    场景:服务端的某一个数据状态定期变化,前端需要定时的去服务端取这个状态

    对于这种场景,有两种解决方案

    1)长轮询(定时器,定时访问接口)

    2)websocket(浏览器兼容性不好)

    {
    	let ajax=function* (){
    		yield new Promise(function(resolve,reject){
    			setTimeout(function(){
    				resolve({code:0})
    			},200)
    		})
    	}
    
    	let pull=function(){
    		let generator=ajax()
    		let step=generator.next()
    		step.value.then(function(d){
    			if(d.code!=0){
    				setTimeout(function(){
    					console.log('wait')
    					pull()
    				},1000)
    			}else{
    				console.log(d)
    			}
    		})
    	}
    
    	pull()
    }

     输出结果为

    {code: 0}

    将resolve({code:0})中code改成1,会一直轮询,输出结果为

    wait
    wait
    wait
    ...
    

      

  • 相关阅读:
    Hamming Distance(随机算法)
    Difference Between Primes
    Pet(dfs)
    29. Divide Two Integers
    28. Implement strStr()
    25. Reverse Nodes in k-Group
    24. Swap Nodes in Pairs
    23. Merge k Sorted Lists
    22. Generate Parentheses
    19. Remove Nth Node From End of List
  • 原文地址:https://www.cnblogs.com/knyel/p/7844787.html
Copyright © 2011-2022 走看看