async 函数是终极异步解决方案,使得异步操作变得更加方便。
1,async的用法。它作为一个关键字放到函数前面,用于表示函数是一个异步函数, 异步函数也就意味着该函数的执行不会阻塞后面代码的执行。 async会返回promise对象。
async function fun(){
return "hello world!";
}
console.log(fun())
说明:async 函数返回的是一个promise 对象,如果要获取到promise 返回值,要用then 方法 ↓ 。
async function fun(){
return "hello world!";
}
fun().then(re => {
console.log(re)
})//hello world!
2,如果函数内部抛出错误, promise 对象有一个catch 方法进行捕获,await意思是"等待", 关键字只能放到async 函数里面。
async function timeout() {
const promise=new Promise((resolve,reject)=>{
setTimeout(()=>resolve('hello world'),2000)
})
// 错误信息
const error=false;//如果为true咋报错
if(!error){
//等resolve执行完了才执行下一步
const res=await promise;
return res;
}else{
await promise.reject(new Error("报错了"));
}
}
timeout()
.then(orr=>console.log(orr))//
.catch(err=>console.log(err));//打印错误信息
3,请求数据
async function getUser(){
const response=await fetch("http://jsonplaceholder.typicode.com/users");//接口地址
const data=await response.json();
return data;
}
getUser().then(users=>console.log(users));
说明:调用getUser方法请求接口,成功以后赋值给data然后返回。await请求接口成功以后才会进行下一步。