async awit 实现axios继发与并发

在使用async awit之前先确定项目支不支持(不支持报 regeneratorRuntime is not defined)

使用webpack搭建的项目可使用 这里 提供webpack配置支持 

  • 使用babel-preset-stage-3、 babel-polyfill 或 babel-plugin-transform-runtime  注意babel v6、v7版本配置稍有不同

继发 

//使用async awit 
asyncPrint = async () => {
        try {
            const t1 = await http.get('demandUser/getUserInfo'); //http为axios实例
            const t2 = await http.post('buy/refund1', { ordernum: t1.num });
            const t3 = await http.post('buy/refund2', { ordernum: t2.num });
        }catch (err) {
            console.log(err);
        }
};

//不使用sync awit     
    print = () => {
        http.get('demandUser/getUserInfo').then((t1) => {
            http.post('buy/refund1', {
                ordernum: t1.num
            }).then((t2) => {
                http.post('buy/refund2', {
                    ordernum: t2.num
                }).then((data) => {

                }).catch((err) => {

                })
            }).catch((err) => {

            })
        });
    };

并发

    asyncPrint = async () => {
        try {
            let t1 = http.get('demandUser/getUserInfo');
            let t2 = http.post('buy/refund1', { ordernum: t1.num });
            let t3 = await http.post('buy/refund2', { ordernum: t2.num });
            await t1;
            await t2;
            await t3;
        }catch (err) {
            console.log(err);
        }
    };

    print = () => {
        http.get('demandUser/getUserInfo')
          .then((t1) => {

        }).catch((err) => {

        });
        http.post('buy/refund1',{
        }).then((data)=>{

        }).catch((err) => {

        });
        http.post('buy/refund2',{
        }).then((data)=>{

        }).catch((err) => {

        });
    };

这里明显使用async awit在处理多次请求时代码量更少且更像同步操作 

异步方式参考 阮一峰 async 

你可能感兴趣的:(react)