美文网首页
异步进化

异步进化

作者: yimi珊 | 来源:发表于2020-09-12 00:37 被阅读0次

    例如:
    获取用户数据;
    再根据用户数据,获得订单数据;
    再根据订单数据,获得商品数据;

    setTimeout

    //回调地狱
    setTimeout(()=>{
      let users = '用户数据'
      console.log(users);
      setTimeout(() => {
        let orders = '订单数据'
        console.log(orders);
        setTimeout(() => {
            let goods = '商品数据'
            console.log(goods);
        }, 1000);
      }, 1000);
    },1000);
    

    生成器函数

    function getUsers(){
      setTimeout(() => {
        let data = '用户数据';
        console.log(data);
        //调用next方法,并且将数据传入
        iterator.next(data);
      }, 1000);
    }
    function getOrders(){
      setTimeout(() => {
        let data = '订单数据';
        console.log(data);
        iterator.next(data);
      }, 1000);
    }
    function getGoods(){
      setTimeout(() => {
        let data = '商品数据';
        console.log(data);
        iterator.next(data);
      }, 1000);
    }
    //声明生成器函数
    function * gen(){
      let users = yield getUsers();
      let orders = yield getOrders();
      let goods = yield getGoods();
    }
    //调用生成器函数
    let iterator = gen();
    iterator.next();
    

    Promise对象

    const p = new Promise((resolve,reject)=>{
        setTimeout(() => {
            let data = '用户数据';
            console.log(data);
            resolve(data);
        }, 1000);
    });
    p.then(value=>{
        return new Promise((resolve,reject)=>{
            setTimeout(() => {
                let data = '订单数据';
                console.log(data);
                resolve([value,data]);
            }, 1000);
        });
    }).then(value=>{
        return new Promise((resolve,reject)=>{
            setTimeout(() => {
                let data = '商品数据';
                console.log(data);
                resolve([value,data]);
            }, 1000);
        });
    });
    

    Async...await

    function getUsers(){
        return new Promise((resolve,reject)=>{
            setTimeout(() => {
                let data = '用户数据';
                // console.log(data)
                resolve(data);
            }, 1000);
        })
    }
    function getOrders(){
        return new Promise((resolve,reject)=>{
            setTimeout(() => {
                let data = '订单数据';
                resolve(data);
            }, 1000);
        })
    }
    function getGoods(){
        return new Promise((resolve,reject)=>{
            setTimeout(() => {
                let data = '商品数据';
                resolve(data);
            }, 1000);
        })
    }
    async function main(){
        let users = await getUsers();
        console.log(users);
        let orders = await getOrders();
        console.log(orders);
        let goods = await getGoods();
        console.log(goods);
    }
    main();
    

    相关文章

      网友评论

          本文标题:异步进化

          本文链接:https://www.haomeiwen.com/subject/lukfzctx.html