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

问题描述 投票:1回答:3

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

await axios.put(`/user/` + this.data.id, this.user)
  .then((response) => {
    this.$router.go();
  })
  .catch((error) => {
    this.$router.go();
  });
javascript es6-promise
3个回答
1
投票

在Axios中,您可以按照official docs这样操作>

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

0
投票

您可以使用Promise的finally方法:


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.