reactjs - React Native Axios 调用内部函数
问题描述
我试图将 AXIOS 函数的 POST 放在另一个函数中以多次重用它。但不幸的是它没有像我预期的那样工作(使用 FETCH 工作),
AXIOS CALL JS:
export async function post(apiRoute, body) {
try {
body = JSON.stringify(body);
axios.post(apiRoute, body, httpOptions)
.then((res)=>{
console.log(res.data); // I have data here
return res.data;
});
}
catch (err) {
console.log(err);
return err;
}
}
来电者是:
async DoLogin(userName, password) {
var data = await post(url,{ // post is axios method defined above in another file
UserName: userName,
Password: password
});
return data; // I have nothing here
}
问题是我在 DoLogin 中未定义但在 POST 方法中获取了数据,似乎问题与时间有关,axions 返回一个在 DoLogin 中无法读取的承诺,我该怎么做?我通过 FETCH 做到了这一点,并且效果很好。
解决方案
尝试以这种方式使用 async-await。
export async function post(apiRoute, body) {
try {
const response = await axios.post(apiRoute, body, httpOptions)
return response.data;
}
catch (err) {
return err;
}
}
推荐阅读
- devops - 如果我从 VS 中的项目中删除一个 cs 文件并从 DevOps 获取最新的,它会返回到项目中吗?
- javascript - 使用 Button 移动数据但只有 True Entries
- kubernetes - 作业无效:“选择器”未自动生成
- sql - SQL 输出 Y/N 比较来自不同表的日期列
- ios - MPRemoteCommandCenter playCommand 与 togglePlayPauseCommand?
- dataframe - 使用 UDF 比较和更新两个 DF
- c++ - 如何通过按下 MFC 对话框中的按钮来停止 while 循环
- c# - 将客户端证书传递给 ASP.NET 中的另一个微服务
- stata - 基于另一个观察值的逻辑
- r - 用另一行的值逐列替换特定的 NA