在Quasar/Vue项目中等待Axios调用完成的问题求解
问题根因
update_Members_data_term函数没有返回axios请求的Promise实例,外部无法感知请求的完成状态testFunction2未声明为异步函数,内部也没有等待接口请求完成就结束执行,外层对它加await不会生效- 直接将异步请求的返回值(Promise对象)赋值给
this.ex,而非请求成功后的实际返回结果
修改后的代码
1. 接口请求函数修改
function update_Members_data_term(term) { // 新增return返回Promise实例 return axios.get( 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi', { params: { db: 'pubmed', api_key: '', retmode: 'json', retmax: 200, term: term } } ).then(response => { // 这里无需async修饰,直接返回结果即可 return response.data.esearchresult.idlist; }).catch(error => { console.log(error.response) }) }
2. 业务函数修改
Global ex=''; testFunction3(arg){ console.log(arg) }, // 声明为异步函数 async testFunction2(){ // 等待接口返回结果后再赋值给this.ex this.ex = await update_Members_data_term("@musc.edu"); }, async testFunction(){ await this.testFunction2() this.testFunction3(this.ex) },
补充说明
如果需要处理接口请求失败的场景,可以在testFunction2里用try/catch包裹await逻辑,避免接口报错导致后续逻辑中断。
内容的提问来源于stack exchange,提问作者Bill
相关产品推荐
相关产品推荐

