DevonDahon
DevonDahon

Reputation: 8350

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();
  });

Upvotes: 4

Views: 818

Answers (4)

Thomas
Thomas

Reputation: 12637

What you actually mean is this:

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

because the only difference between the code you wrote and this one is: if this.$router.go() throws an error, then call this.$router.go() again. Doesn't make much sense.

And since you don't care about the response either, you can as well write:

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

or better (IMO)

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

this.$router.go();

assuming you have defined function noop(){} somewhere else for further use.

Even if it's said that you should not mix promise.then() and await, I prefer this over

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

this.$router.go();

Upvotes: 0

kiranvj
kiranvj

Reputation: 34117

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

In Axios you can do like this as per the official docs

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

Update: Checked this after comment by @CertainPerformance

Axios now supports finally (Check under examples)

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370759

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(() => {});

Upvotes: 2

Related Questions