Search code examples
javascriptes6-promise

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

Solution

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