使用 async await 遇到的问题
错误案例,外面接收不到数据
async handleFindByRowId(rowId) {
let url = '/findByRowId?rowId=' + rowId
await this.$http.get(url).then(async res => {
if (res.data.success) {
resData = res.data.data
}
})
.catch(error => {
this.$message({ type: 'error', message: error })
})
}
在上面代码中,外部调用 await this.handleFindByRowId('12345'),无法接收到接口请求的数据,而是需要这样使用
方案一:
async handleFindByRowId123() {
return { a: '1' }
)
console.log(await this.handleFindByRowId123(), '这里可以获取到数据啦啦啦啦')
方案二:
handleFindByRowId2222() {
return new Promise((resolve, reject) => {
let url = '/findByRowId?rowId=' + rowId
this.$http.get(url).then( res => {
if (res.data.success) {
resolve(res.data.data || {})
resData = res.data.data
}
})
.catch(error => {
this.$message({ type: 'error', message: error })
reject({})
})
}
})
)
console.log(await this.handleFindByRowId2222(), '这里可以获取到数据啦啦啦啦')
如何让请求接口顺序执行
async handleFindByRowId(rowId) {
let url = '/findByRowId?rowId=' + rowId
await this.$http.get(url).then(async res => {
if (res.data.success) {
console.log('这里会先执行完在执行下面的打印11111')
}
})
.catch(error => {
this.$message({ type: 'error', message: error })
})
}
const resData = await this.handleFindByRowId()
console.log('这里会在接口执行完后再次执行吧吧吧吧2222222')