【发布时间】:2021-10-02 15:12:53
【问题描述】:
我正在尝试执行以下步骤:
第 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 });
});
【问题讨论】:
-
您应该查看这个问题:stackoverflow.com/questions/14220321/…
标签: javascript reactjs promise axios next.js