javascript - 如何从嵌套的 Axios 调用返回值?

标签 javascript reactjs promise axios next.js

我正在尝试执行以下步骤:

第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 });
});

最佳答案

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

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

关于javascript - 如何从嵌套的 Axios 调用返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68533954/

相关文章:

typescript - typescript promise 响应/错误的一般处理

javascript - jquery 从节点列表中删除节点

javascript - 将 JavaSscript 构造函数属性传递给 mouseover 函数并仍然使用 d3.select(this)

javascript - 处理 JavaScript 中被遗忘的 Promise

node.js - Webpack 突然无法编译,因为 "Module not found: Error: Can' tsolve"错误

reactjs - 我们可以将 React 组件集成到 Aurelia 项目中吗?

redis - 为什么在使用 node 和 redis 时我的 promise 没有解决?我的数组返回第一次迭代而不是等待整个代码运行

java - 如何从 JSP 访问 JavaScript 中的 Java 对象

javascript - Express js 路线从未命中/:id

javascript - 在 React 中无法从父级调用客户端方法?