reactjs - 需要为 axios 创建一个通用函数 .then 和 catch
问题描述
这是我的 controller.js 代码
action = dispatch(userValidateOtp(api_url, API_METHODS.PUT, pData))
return action.then((data) => {
return data
}).catch((reason) => {
try {
return reason.response.data
} catch (error) {
history.push('/error')
return false
}
})
我想要这个返回的通用函数我尝试了异步和等待
错误:=无法读取未定义反应 axios 的属性 'then' - Google 搜索
实用程序.js
export const axiosCall = (reason, history) => {
return action.then(function (data) {
return data;
}).catch((reason) => {
try {
return reason.response.data
} catch (err) {
console.log("demo", err);
history.push('/error')
return false
}
})
}
调用函数:axiosCall(action, history);
解决方案
像这样的东西:-
import axios from 'axios'
async function callApi() {
const data = await withTryCatch(
axios.get('https://random.dog/woof.json')
);
console.log(data)
}
async function withTryCatch(apiCall) {
try {
console.log('inside the withTryCa')
const { data } = await apiCall;
return data;
} catch(err) {
console.log("demo", err);
// history.push('/error')
return false
}
}
推荐阅读
- postgresql - 如何从 c 扩展内部执行选择语句
- r - 如何在全球环境 R 中订购多个数据框
- android - ExpandableListAdapter 显示错误的 childViews
- javascript - js 不会等到 promise 完成
- haskell - 关于列表,方括号和括号有什么区别?
- blazor - Blazor 仅在移动设备上显示组件
- javascript - 如何在 Django 模板中使用 filepond javascript 库?
- python - 如何将数据框列直接转换为以列值作为列索引的数据框?
- amazon-web-services - AWS CodeDeploy 在通过 AutoScaling 部署时覆盖现有文件
- c++ - 如何外部声明一个外部“C”变量