mardi 11 mai 2021

How to use if else before .then() .catch() in Vue.js?

I'm creating app in Vue.js. I have two similar methods:

    editTool() { 
      return ToolService.editTool(this.id, this.editedItem)
        .then((response) => {
          this.$refs.dialogInfo.setSuccess(response);
        })
        .catch((error) => {
          this.$refs.dialogInfo.setError(error);
        })
        .finally(() => {
          this.$emit("completed");
        });
    },

    newTool() {
      return ToolService.addTool(this.editedItem)
        .then((response) => {
          this.$refs.dialogInfo.setSuccess(response);
        })
        .catch((error) => {
          this.$refs.dialogInfo.setError(error);
        })
        .finally(() => {
          this.$emit("completed");
        });
    },

They only differ in the value in return, rest is the same. I want to turn these two methods into one. I tried this way:

    newMethod() {
      if (this.edit) return ToolService.editTool(this.id, this.editedItem);
      else
        return ToolService.addTool(this.editedItem)
          .then((response) => {
            this.$refs.dialogInfo.setSuccess(response);
          })
          .catch((error) => {
            this.$refs.dialogInfo.setError(error);
          })
          .finally(() => {
            this.$emit("completed");
          });
    },

But it doesn't work correct. How to do it?

Aucun commentaire:

Enregistrer un commentaire