zoukankan      html  css  js  c++  java
  • Generator函数——ES6异步编程

    1.Generator函数详解

    作用:1.延迟执行的异步函数;2.与Symbol.iterator的关系;3.状态机

    定义一个Generator函数

    function* myGenerator(){
    
        console.log('开始');
    
        let res = yield "暂停一";
        console.log(res);
    
        console.log('继续');
    
        yield "暂停二";
    
        console.log('继续二');
    
        return '结束';
    }
    //调用Generator函数并不是马上开始执行代码,而是返回一个执行方法的指针
    myGenerator();//不能直接调用
    let point = myGenerator();
    //让Generator函数启动
    point.next();
    
    /*
    
    让Generator函数启动,碰到yield语句的时候就暂停了,
    yield语句,会将一个对象->{value:'暂停一',done:false},会作为next函数的返回值
        value:表示yield的值或return表达式的结果
        done:表示是否结束
    
    */
    console.log(point.next());//{value:'暂停一',done:false}
    console.log(point.next());//{value:'暂停二',done:false}
    
    //第一句next语句传入的参数是没有意义的,因为它有口饭吃的是函数,不是uield语句
    console.log(point.next('hello'));
    console.log(point.next('world'));//打印world

    2.Generator函数案例

    1.通过Generator函数来部署iterator接口

    let obj = {
        name:'tom',
        age:19,
        sex:'man'
    }
    //手动部署iterator接口
    //所有能够使用for of 遍历的对象,iterator接口都部署在symbol.iterator属性
    obj[Symbol.iterator] = function*(){
        /*yield 1;
        yield 2;
        yield 3;*/
        for(let key of obj){
            yield obj[key]
        }
    }
    for(let value of obj){
        console.log(value)
    }

    2.页面的砸金蛋,限定砸金蛋的次数

    //定义一个砸金蛋的Generator函数
    function* hitEgg(count){
        while(count>0){
            count--;
            yield console.log(`砸金蛋了!还可以砸${ocunt}次!`);
        }
    }
    
    //从服务器获取剩余次数,传入Generator函数
    let draw = hitEgg(5);
    
    $(function(){
        $('#btn').click(() => {
            draw.next();
        })
    })

    3.Generator函数发送异步请求

    先获取商品详情,在获取商品评论

    总结:使用Generator函数发送异步请求:
    1.逻辑清晰
    2.避免了’回调地狱;
    3.可以灵活的控制各个请求发送的时机

    function* getGoods(){
        //先获取商品详情页
        let commentsUrl = yeild getData('http://localhoset:3000/goos_detail?id=2');
        //再获取商品评论内容
        yield getData(commentsUrl);
    }
    function getData(url){
        $.get(url,(data) => {
            console.log(data);
            //第二次调用next,将商品评论的url传入下一次的yield
            geneGood.next(`http://localhoset:3000${data.commentsUrl}`);
    
        },'json')
    }
    let geneGood = getGoods();
    // 第一次调用next函数,发送请求商品详情的ajax
    geneGood.next();
  • 相关阅读:
    tomcat调优
    使用Docker部署Spring Boot项目
    java配置ueditor中解决“未找到上传文件”错误提示
    java.lang.NoClassDefFoundError: org/aspectj/weaver/reflect/ReflectionWorld$ReflectionWorldException
    spring01
    android中的wrap_content,match_parent, fill_parent
    RPC和http
    Failed to read artifact descriptor for xxx
    Error processing condition on org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration$ThymeleafWebMvcConfiguration.resourceUrlEncodingFilter
    springboot的自动配置
  • 原文地址:https://www.cnblogs.com/lisa2544/p/15660820.html
Copyright © 2011-2022 走看看