[英]Make second api call when there is no error on the first using Axios in React
I have three API calls which should be dependent on one another.我有三个 API 调用,它们应该相互依赖。 The second API call should trigger only when the first succeeds.
第二个 API 调用应仅在第一个成功时触发。
With my current implementation, I'm getting a CORS error when the first API call is made and was able to catch the error in the catch
block.在我当前的实现中,当第一次调用 API 并且能够在
catch
块中catch
错误时,我收到了 CORS 错误。 However, I'm seeing that the second and third APIs calls are made irrespective of the error that got caught in the first API call.但是,我发现无论在第一个API 调用中捕获到的错误如何,都会进行第二个和第三个API 调用。
Could anyone please advise?任何人都可以请指教吗?
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();
You're calling the functions synchronously when you need to do it asynchronously:当您需要异步调用函数时,您正在同步调用这些函数:
async function performTasks() {
await firstApiCall();
await secondApiCall();
await thirdApiCall();
}
performTasks();
You can use the ES6 Promise implementation approacg.您可以使用 ES6 Promise 实现 approacg。 Therefore you should take a look to this ressource : [Promise][1]
因此你应该看看这个资源:[Promise][1]
With the promise approach you can react at each step / each API call.使用承诺方法,您可以在每个步骤/每个 API 调用中做出反应。 [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
[1]: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
async
await
functions work only in their local scope. async
await
函数仅在其本地范围内工作。 For example:例如:
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()
What you can do is, use async
await
inside the main function, so that the functions would be called in an order您可以做的是,在 main 函数中使用
async
await
,以便按顺序调用这些函数
const main = async () => {
await myFunc();
await otherFunc();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.