避免在 'then' 和 'catch' 中重复相同的代码

Avoid repeating the same code in 'then' and 'catch'

是否有一个选项可以避免在下面的代码中重复 this.$router.go() 和 运行 一段代码,无论结果如何?

await axios.put(`/user/` + this.data.id, this.user)
  .then((response) => {
    this.$router.go();
  })
  .catch((error) => {
    this.$router.go();
  });

您可以提前将其放入命名函数中:

const handle = () => {
  this.$router.go();
};
await axios.put(`/user/` + this.data.id, this.user)
  .then(handle)
  .catch(handle);

你也可以使用 .finally,如果 Axios 支持它,它是 a bit new,但是 .finally 的一个问题是 Promise 将 "pass through" [=12] =],因此尽管您可以不重复地调用 this.$router.go,但如果 axios 调用被拒绝,您最终会得到一个被拒绝的 Promise。所以你之后需要 .catch 来避免 await 抛出:

await axios.put(`/user/` + this.data.id, this.user)
  .finally(() => {
    this.$router.go();
  })
  .catch(() => {});

您可以使用 Promise 的 finally 方法:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally

...and run a piece of code whatever the result is ?

在 Axios 中,您可以按照 official docs

axios.get('url')
  .then(function (response) {
    // handle success
  })
  .catch(function (error) {
    // handle error
  })
  .then(function () {
    // always executed
    this.$router.go();
  });

更新:在@CertainPerformance

发表评论后检查了这个

axios 现在支持finally(查看示例)

你的实际意思是这样的:

await axios.put(`/user/` + this.data.id, this.user)
  .then((response) => {
    this.$router.go();
  },(error) => {
    this.$router.go();
  });

因为您编写的代码与此代码之间的唯一区别是:如果 this.$router.go() 抛出错误,则再次调用 this.$router.go()。没有多大意义。

因为你也不关心 response,你也可以写:

await axios.put(`/user/` + this.data.id, this.user)
  .catch(() => {})
  .then(() => {
    this.$router.go();
  });

或更好 (IMO)

await axios.put(`/user/` + this.data.id, this.user).catch(noop);

this.$router.go();

假设您已经在其他地方定义了 function noop(){} 以供进一步使用。

虽然说 promise.then()await 不能混用,但我更喜欢这个而不是

try {
  await axios.put(`/user/` + this.data.id, this.user);
} catch (error) {}

this.$router.go();