async
- async修饰函数返回的是一个Promise对象,可以使用then函数添加回调函数
await
- await修饰的如果是promise对象,可以获取到promise中返回的内容(resolve和reject参数),且取到值后语句才会往下执行.
- 如果不是promise对象,把这个非promise的东西当作await表达式的结果.
实现
created() {
this.getList();
},
methods: {
async getList() {
// 同步1
console.log("同步1",await this.synchronize(300));
// 同步2
await this.synchronize(100).then(res => {
console.log("同步2",res);
});
// 异步1
this.synchronize(200).then(res => {
console.log("异步1",res);
});
// 异步2
console.log("异步2");
// 异步3
this.synchronize(50).then(res => {
console.log("异步3",res);
});
},
// 同步方法
synchronize(time){
// 返回Promise对象
return new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve(time)
},time)
})
},
},
结果
同步1 300
同步2 100
异步2
异步3 50
异步1 200