调用Axios时出现问题,从返回数据,然后箭头函数始终未定义

toiithl6  于 2022-10-21  发布在  iOS
关注(0)|答案(2)|浏览(157)

我有以下代码:

getData = async function (afgJSON) {
      console.log("step 2")
      await axios.post(process.env.afgEndPoint, afgJSON, {
          headers: headers
        })
        .then((response) => {
          console.log("step 3")
          return response.data
        })
        .catch((e) => {
          console.log("step 3")
          return e.response.data    
        })
    }

我这样称呼它:

console.log("step 1")
let afgResponse = await common.getData(afgJSON);
console.log("step 4")
console.log(afgResponse)

AfgResponse始终是未定义的,并且console.log显示正确的顺序:
步骤1
步骤2
步骤3
第四步
未定义
..。但是,如果我sole.log响应.data(.Then),则响应是正常的。
我在Stackoverflow上阅读了其他关于Axios的帖子,但我仍然无法理解这一点。
谢谢。

gkl3eglg

gkl3eglg1#

您错过了从函数“getData”返回axios调用的结果

qoefvg9y

qoefvg9y2#

getData = async function (afgJSON) {
    try {
      const { data } = await axios.post(process.env.afgEndPoint, afgJSON, {
          headers: headers
        })
      return data
    } catch (err) {
      return err // return the data you want
    }
}

您也可以直接返回axios.post和check

getData = async function (afgJSON) {
      return axios.post(process.env.afgEndPoint, afgJSON, {
          headers: headers
        })
}

在您的其他文件中=>

const { data: afgResponse } = await common.getData(afgJSON);

但您必须处理另一个文件中的错误

相关问题