如何从嵌套Axios调用中正确返回值?分支场景返回undefined如何解决
问题根因
- 核心问题:
createProfileByUserIDNew作为async函数,在拿到await的执行结果后没有显式return返回值,导致函数默认返回的Promise resolve值为undefined。 - 次要问题1:async/await和.then()链式调用混用,逻辑冗余容易引发理解偏差,增加出错概率。
- 次要问题2:catch分支仅打印错误没有向外抛出,异常会被静默吞掉,调用方无法感知请求失败的情况。
- 调用代码问题:then的回调使用普通function声明,内部this指向不指向组件实例,执行setState时会报错。
修复方案
推荐使用纯async/await写法,逻辑更清晰易维护:
async createProfileByUserIDNew(data, email) { try { const AuthStr = 'Bearer ' + getToken(); // 步骤1:查询对应记录 const getRes = await axios.get(`${baseUrl}/buyer-profiles?user_email=${email}`, { headers: { Authorization: AuthStr }, }); // 步骤3:记录存在直接返回查询结果 if (getRes.data.length !== 0) { return getRes; } // 步骤2:记录不存在发起创建请求 const postRes = await axios.post(`${baseUrl}/buyer-profiles`, data, { headers: { Authorization: AuthStr }, }); return postRes; } catch (error) { console.log(JSON.stringify(error)); // 抛出错误供调用方捕获处理 throw error; } }
如果要保留原有的.then链式写法,只需在函数末尾添加return即可:
async createProfileByUserIDNew(data, email) { const AuthStr = 'Bearer ' + getToken(); const response = await axios .get(`${baseUrl}/buyer-profiles?user_email=${email}`, { headers: { Authorization: AuthStr }, }) .then((response) => { if (response.data.length === 0) { return axios.post(`${baseUrl}/buyer-profiles`, data, { headers: { Authorization: AuthStr }, }); } else { return response } }) .then((response) => { return response; }) .catch((error) => { console.log(JSON.stringify(error)) throw error; }); // 新增这行返回结果 return response; }
调用代码修复(修正this指向,增加异常处理)
const ret = createProfileByUserIDNew(data, user.email); // 用箭头函数保证this指向组件实例 ret.then((response) => { console.log(response); this.setState({ buyerProfileId: response.items.id }); }).catch(error => { // 可补充请求失败的业务处理逻辑 console.error('操作失败', error); });
内容的提问来源于stack exchange,提问作者Sona Shetty
相关产品推荐
相关产品推荐

