Axios 完成事件

3

我正在使用 Axios 进行 API 服务,想知道是否有官方的方式来处理“完成”事件,就像我们在 Ajax 调用中所使用的那样。

就像这样:

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

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally - Brian Lee
2个回答

8

根据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

0
如果您需要检查 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/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接