【问题标题】:How to return values from a nested Axios call?如何从嵌套的 Axios 调用中返回值?
【发布时间】: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 });
});

【问题讨论】:

标签: javascript reactjs promise axios next.js


【解决方案1】:

请记住,async/await 是链接 .then()、.catch() 和 .finally() 的其他承诺语法的“语法糖”;换句话说,它允许您在看起来更同步的代码中处理这些类型的异步操作。

const createProfileByUserIDNew = async (data, email) => {
  const AuthStr = "Bearer " + getToken();

  try {
    // we're awaiting this response, so we don't need to chain a .then()
    // we could even destructure response into the objects we'll need later, 
    // i.e. const { data } = await axios.get(...)
    const response = await axios.get(
      `${baseUrl}/buyer-profiles?user_email=${email}`,
      {
        headers: { Authorization: AuthStr },
      }
    );
    if (response.data.length === 0) {
      // do the things we need to do when we don't get the data we want
      // once again, we don't have to chain a then() to this; you may
      // have heard that 'return await' is redundant and causes some 
      // problems, but since we're in a try/catch it's ok
      // see https://jakearchibald.com/2017/await-vs-return-vs-return-await/
      return await axios.post(`${baseUrl}/buyer-profiles`, data, {
        headers: { Authorization: AuthStr },
      });
    } else {
      // the user exists, so we'll do other things, like maybe return the 
      // original response or something
      return response;
    }
  } catch (error) {
    console.error("We hit a snag:", error);
  }
};

// now when we call this method (must be called from another async function), the same principles apply
const ret = await createProfileByUserIDNew(data, user.email);
console.log(ret);
This.setState({ buyerProfileId: ret.data.items.id });

【讨论】:

  • @Sona Shetty 应该提到这可能需要一些调整,尤其是在处理错误的方式方面(因为您的异步函数中有两个可能会拒绝的承诺);希望这会让你走上正确的道路!
【解决方案2】:

这是因为当您简单地执行return response 时,您返回的是请求的响应,而不是Promise。在进行axios.post() 调用时,您应该只链接.then(),因为这实际上返回了Promise

另外,如果您想以目前的方式使用createProfileByUserIDNew 函数,您需要直接从axios.get 返回Promise

async createProfileByUserIDNew(data, email) {
    const AuthStr = 'Bearer ' + getToken();
    return axios.get(`${baseUrl}/buyer-profiles?user_email=${email}`, {
            headers: { Authorization: AuthStr },
        })
        .then((response) => {
            if (response.data.length === 0) {
                return axios.post(`${baseUrl}/buyer-profiles`, data, {
                        headers: { Authorization: AuthStr },
                    })
                    .then((response) => {           
                        return response;
                    });
            } else {
                return response;
            }
        })
        .catch((error) => console.log(JSON.stringify(error)));
}

【讨论】:

    猜你喜欢
    • 2013-10-26
    • 1970-01-01
    • 1970-01-01
    • 2015-03-15
    • 1970-01-01
    • 1970-01-01
    • 2016-04-10
    • 2019-09-19
    • 2022-07-03
    相关资源
    最近更新 更多