javascript - 如何从嵌套的 Axios 调用中返回值?
问题描述
我正在尝试执行以下步骤:
步骤 1:调用 Axios 以检查数据库中是否存在记录。
第 2 步:如果记录没有退出,则进行 POST API 调用以创建数据并返回 POST 响应。
第 3 步:如果记录已存在,则返回第 1 步的响应
第 1 步和第 2 步工作正常,我可以从createProfileByUserIDNew
. 当步骤 3 的代码块被执行时createProfileByUserIDNew
,不会返回任何值。
有人可以告诉我我做错了什么吗?
async createProfileByUserIDNew(data, email) {
const AuthStr = 'Bearer ' + getToken();
const response = await axios
.get(`${baseUrl}/buyer-profiles?user_email=${email}`, {
headers: { Authorization: AuthStr },
})
.then((response) => {
//*****This block return proper value in the next then
if (response.data.length === 0) {
return axios.post(`${baseUrl}/buyer-profiles`, data, {
headers: { Authorization: AuthStr },
});
//~~~~~~~This block return proper value in the next then
//*****This block does not return any value in the next then
} else {
return response //Return response from first axios call
}
//*****This block does not return any value in the next then
})
.then((response) => {
return (response); //Step 2 return the value but step 3 return undefined
})
.catch((error) => console.log(JSON.stringify(error)));
}
调用上述方法:
const ret = createProfileByUserIDNew(
data,
user.email
);
ret.then(function (response) {
console.log(response); //Setp 2 returns proper value but step 3 return undefined
this.setState({ buyerProfileId: response.items.id });
});
解决方案
请记住,async/await 是链接 .then()、.catch() 和 .finally() 的其他承诺语法的“语法糖”;换句话说,它允许您在看起来更同步的代码中处理这些类型的异步操作。
const createProfileByUserIDNew = async (data, email) => {
const AuthStr = "Bearer " + getToken();
try {
// we're awaiting this response, so we don't need to chain a .then()
// we could even destructure response into the objects we'll need later,
// i.e. const { data } = await axios.get(...)
const response = await axios.get(
`${baseUrl}/buyer-profiles?user_email=${email}`,
{
headers: { Authorization: AuthStr },
}
);
if (response.data.length === 0) {
// do the things we need to do when we don't get the data we want
// once again, we don't have to chain a then() to this; you may
// have heard that 'return await' is redundant and causes some
// problems, but since we're in a try/catch it's ok
// see https://jakearchibald.com/2017/await-vs-return-vs-return-await/
return await axios.post(`${baseUrl}/buyer-profiles`, data, {
headers: { Authorization: AuthStr },
});
} else {
// the user exists, so we'll do other things, like maybe return the
// original response or something
return response;
}
} catch (error) {
console.error("We hit a snag:", error);
}
};
// now when we call this method (must be called from another async function), the same principles apply
const ret = await createProfileByUserIDNew(data, user.email);
console.log(ret);
This.setState({ buyerProfileId: ret.data.items.id });
推荐阅读
- javascript - 与其他浏览器相比,IE11 渲染/加载图标较晚
- objective-c - 出现错误“在框架模块中包含非模块化标头”
- python - 是否允许在 Python 中使用子类构造函数
- sql-server - 添加身份迁移时表已存在
- gitlab - 如何限制来宾用户克隆存储库
- php - 简单的日期访客计数器计数文本行
- javascript - 在 reactJS 中显示后端数据
- c# - 如何实现从数据库(按需)加载配置值的 IConfigurationProvider?
- javascript - Google Directions API - 前往更广阔区域的路线
- jasmine - 量角器跨度重复循环