如何正确的使用async 函数

3 篇文章 0 订阅
3 篇文章 0 订阅

使用 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
async handleFindByRowId(rowId) {
				let url = '/findByRowId?rowId=' + rowId
				// 接口前添加 await 延迟执行
				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')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值