async用来表示函数是异步的,定义的async函数返回值是一个promise对象,可以使用then方法添加回调函数。
await 用于等待一个异步方法执行完成,await 必须出现在 async 函数内部,不能单独使用。 函数中只要使用await,则当前函数必须使用async修饰
示例1:一个请求接着一个请求,而后一个请求依赖前一个请求
async created() {
// 需要等到上个代码执行完拿到值再做其他操作
await this.userData(); //这里可以拿到userType
//拿到userType 判断用户不是代理人展示不同信息
if(this.userType==1){
this.isAgent=true;
}
}
示例2:使用 Promise.all 配合 Async,可以使用 Promise.all 方法来同时处理多个异步操作,例如
async function fetchData() {
const promise1 = axios.get('/data1');
const promise2 = axios.get('/data2');
const promise3 = axios .get('/data3')
const [data1 data2, data3] = await Promise.all(promise1, promise2, promise3]);
return {data1: data1.data , data2: data2.data, data3: data3.data};
}
fetchData().then((data) => (
console.log(data);
})
使用 Promise.all方法来同时获取多个远程数据,并将数据分别存储在 data1、data2和 data3变量中。