首页 > 解决方案 > 需要为 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);

标签: reactjsreact-native

解决方案


像这样的东西:-

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
   }
}


推荐阅读