javascript - 如何调用返回值是异步请求函数的函数

查看:140
本文介绍了javascript - 如何调用返回值是异步请求函数的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

在vue的methods,函数search作用是返回请求数据,但是报错

search(options) {
  const url = this.isTeacher? '/api/search_Teacher' : '/apis/org/search_student';
  const params = options.ids ? { ids: options.ids } : { keyword: this.keyword };
 return this.$http.get(url, { params }).then((response) => {
   return response.body;
  }, (err) =>{
   console.log(err);
  })
},

但是不明白如何调用这个search,获取到data??
尝试下面的方法,报错,this.search is not a function??

  this.seach({ ids: this.selected }).then((res) => {
    if (!res) this.$message.error('搜索失败');
    else this.selectedData = res;
  });

有没有好的方法,谢谢

解决方案

async search(options) {
  const url = this.isTeacher? '/api/search_Teacher' : '/apis/org/search_student';
  const params = options.ids ? { ids: options.ids } : { keyword: this.keyword };
  try {
    const res = await this.$http.get(url, { params })
    return res.body
  } catch (e) {
    console.log(e)
  }
},

use

const data = await this.search({ ids: this.selected })
if (!data) this.$message.error('搜索失败');
else this.selectedData = data;

这篇关于javascript - 如何调用返回值是异步请求函数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆