Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is there an option to avoid repeating this.$router.go() in the code below and run a piece of code whatever the result is ?

await axios.put(`/user/` + this.data.id, this.user)
  .then((response) => {
    this.$router.go();
  })
  .catch((error) => {
    this.$router.go();
  });
like image 773
DevonDahon Avatar asked Oct 18 '25 16:10

DevonDahon


2 Answers

You can put it into a named function ahead of time:

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

You could also use .finally, if Axios supports it, it's a bit new, but a problem with .finally is that the Promise will "pass through" the .finally, so although you'll be able to call this.$router.go without repetition, if the axios call rejects, you'll end up with a rejected Promise. so you'll need to .catch afterwards to avoid the await from throwing:

await axios.put(`/user/` + this.data.id, this.user)
  .finally(() => {
    this.$router.go();
  })
  .catch(() => {});
like image 145
CertainPerformance Avatar answered Oct 20 '25 05:10

CertainPerformance


You can use the finally method of a Promise:

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

like image 41
Emanuele Scarabattoli Avatar answered Oct 20 '25 06:10

Emanuele Scarabattoli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!