ES6 语法之 async 函数

一、概念

async 函数跟上文讲到的 Generator 函数作用几乎差不多,只不过是 Generator 函数的优化版。

二、特点

相比 Generator 函数具备以下特点:

1.定义时在 funtion 前面用 async ,取代 Generator 函数 funtion 后面的*;

2.语句内用 await 关键字,取代 Generator 函数的 yield;

3.返回值是 promise 对象,而不是 Iterator 遍历器,可通过 then 方法添加成功或失败函数;

4.直接调用,自动执行,不需要通过next方法。

async function x() {
        await new Promise(function (resolved, rejected) {
            setTimeout(resolved, 2000);
        })
        console.log(111);//2秒钟输出111
    };
    x();//是一个promise对象

三、应用

分别使用 Promise 、Generator、async 实现接口数据获取成功后打印出"获取数据成功"。

   //Promise实现
    function sync() {
      return new Promise(function (resolve,reject) {
            getData(resolve);
        });
    };
    sync().then(function (res) {
        console.log('通过Promise获取数据成功'+res);
    });
    //Generator实现
    function* gen() {
        yield new Promise(function (resolve,reject) {
            getData(resolve);
        });
        console.log('通过Generator获取数据成功');
    };
    var obj = gen();
    obj.next();
   
    //async实现
    async function x() {
        await new Promise(function (resolve,reject) {
            getData(resolve);
        });
        console.log('通过async获取数据成功');
    };
    x();

    //获取接口数据公共方法
    function getData(resolve){
        const client = new XMLHttpRequest();
        client.open('GET', url);
        client.responseType = 'json';
        client.send();
        client.onreadystatechange = function () {
            if (this.readyState !== 4) {
                return;
            }
            if(this.status == 200){
                console.log(this.response);
                resolve(this.response)
            }else {
                reject(new Error(this.statusText))
            }
        };
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值