概念:
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))
}
};
}