Axios完成活动



我正在使用Axios为API服务,只是想知道是否有任何正式的方法来处理;完整的";事件,正如我们在Ajax调用中使用的那样。

就像

axios.get('/v1/api_endpoint?parameters')
.then((res) => { .. })
.catch((err) => { .. })
.complete(() => {})     //  <== is there any way to handle this complete event? 

根据这里的axios文档,我正在寻找辅助.then((

这里有一个很好的例子,说明如何处理axios完成事件,无论成功还是失败,该事件都将始终执行。

axios.get('/v1/api_endpoint?with_parameters')
.then((res) => { // handle success })
.catch((err) => { // handle error })
.then(() => { // always executed })        <-- this is the one

如果您必须检查API调用是否成功,那么您可以使用以下代码:

const response = await axios.post(
"http://localhost:8000/xyz",
{ token, user }
);
const status = response.status
if (status == 200) {
console.log('Success')
toast("Successful Transaction", { type: "success" });
} else {
console.log('Falure')
toast("Falure", { type: "error" });
}

您也可以使用finally来检查事件是否已完成。附上链接供您参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally

最新更新