1.先异步,后同步,不需要返回值
test(){
return new Promise(resolve=>{
setTimeout(()=>{
console.log('异步数据')
resolve() //不需要返回值
},2000)
})
},
async search(){
await this.test() //不需要返回值
console.log('同步数据')
},
this.search() 结果为:异步数据 同步数据
2.先异步,后同步,需要返回值
test(){
return new Promise(resolve=>{
setTimeout(()=>{
console.log('异步数据')
resolve('异步数据1') //需要返回值
},2000)
})
},
async search(){
let res = await this.test() //需要返回值
console.log(res)
console.log('同步数据')
},
this.search() 结果为:异步数据 异步数据1 同步数据
3.顺序执行多个异步请求后,再执行同步请求
test(){
return new Promise(resolve=>{
setTimeout(()=>{
console.log('异步数据1')
resolve('异步数据11') //需要返回值
},1000)
})
},
test2(){
return new Promise(resolve=>{
setTimeout(()=>{
console.log('异步数据2')
resolve('异步数据22') //需要返回值
},2000)
})
},
test3(){
return new Promise(resolve=>{
setTimeout(()=>{
console.log('异步数据3')
resolve('异步数据33') //需要返回值
},3000)
})
},
async search(){
let res3= await this.test3() //需要返回值
let res2 = await this.test2() //需要返回值
let res = await this.test() //需要返回值
console.log(res,res2,res3)
console.log('同步数据')
},
this.search() 结果为:
// 异步数据3
// 异步数据2
// 异步数据1
// 异步数据11 异步数据22 异步数据33
// 同步数据