簡體   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