js 生成器的应用

js异步编程学习生成器很好的例子用生成器不写成回调地狱的形式

例1.用生成器实现一个1s后控制台输出111,再2s后控制台输出222,再3s后控制台输出333

    function one(){
        setTimeout(()=>{
            console.log(111);
            iterator.next();
        },1000)
    }
    function two(){
        setTimeout(()=>{
            console.log(222);
            iterator.next();
        },2000)
    }
    function three(){
        setTimeout(()=>{
            console.log(333);
            iterator.next();
        },3000)
    }
    function * gen(){
        yield one();
        yield two();
        yield three();
    }
    let iterator = gen();
    iterator.next();

 

例2.模拟获取 用户数据,订单数据,商品数据

    function getUsers(){
        setTimeout(()=>{
            let data = "用户数据";
            iterator.next(data);
        },1000)
    }
    function getOrders(){
        setTimeout(()=>{
            let data = "订单数据";
            iterator.next(data);
        },1000)
    }
    function getGoods(){
        setTimeout(()=>{
            let data = "商品数据";
            iterator.next(data);
        },1000)
    }
    function * gen(){
        let users = yield getUsers();
        console.log(users);
        let orders = yield getOrders();
        console.log(orders);
        let goods = yield getGoods();
        console.log(goods);
    }
    let iterator = gen();
    iterator.next();

 

posted @ 2021-09-25 22:33  jerryfish  阅读(237)  评论(0编辑  收藏  举报