繁体   English   中英

当第一次在 React 中使用 Axios 没有错误时进行第二次 api 调用

[英]Make second api call when there is no error on the first using Axios in React

我有三个 API 调用,它们应该相互依赖。 第二个 API 调用应仅在第一个成功时触发。

在我当前的实现中,当第一次调用 API 并且能够在catch块中catch错误时,我收到了 CORS 错误。 但是,我发现无论在第一个API 调用中捕获到的错误如何,都会进行第二个第三个API 调用。

任何人都可以请指教吗?

const firstApiCall = async() => {
  try {
    await axios.post(
      process.env.FIRST_API,
      payload
    );
  ]
} catch (err) {
  console.log(`err`, err);
}
};


const secondApiCall = async() => {
  try {
    await axios.post(
      process.env.SECOND_API,
      payload

    }
  } catch (err) {
    console.log(`err`, err);
  }
};

const thirdApiCall = async() => {
  try {
    await axiosInstance.patch(
      process.env.THIRD_API,
      payload
    );
  } catch (err) {
    console.log('err', err);
  }
};

firstApiCall();
secondApiCall();
thirdApiCall();

当您需要异步调用函数时,您正在同步调用这些函数:

 async function performTasks() {
    await firstApiCall();
    await secondApiCall();
    await thirdApiCall();
  }
  performTasks();

您可以使用 ES6 Promise 实现 approacg。 因此你应该看看这个资源:[Promise][1]

使用承诺方法,您可以在每个步骤/每个 API 调用中做出反应。 [1]: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then

async await函数仅在其本地范围内工作。 例如:

const myFunc = async() => {
  try{
    //...
    await foo();
    //All the code below will be blocked till 
    //the promise return by foo function is resolved
  }
  catch{
    //...
  }
}

const main = () => {
  myFunc();
  otherFunc();
  //Other function calls
  //Regardless of using async await in myFunc, 
  //the code bellow myFunc will be executed as
  //async await will work only in myFunc block scope
}

main()

您可以做的是,在 main 函数中使用async await ,以便按顺序调用这些函数

const main = async () => {
  await myFunc();
  await otherFunc();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM