Vue.js中.then() .catch() 之前如何使用if else?

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

我正在 Vue.js 中创建应用程序。我有两个类似的方法:

    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");
        });
    },

仅return中的值不同,其余相同。我想把这两种方法合二为一。我这样试过:

    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");
          });
    },

但它不能正常工作。怎么做?

按照下面的方法试试

editTool() {
    return ToolService.editTool(this.id, this.editedItem)
  },

  newTool() {
    return ToolService.addTool(this.editedItem)
  },

  newMethod() {
    let method = this.newTool;
    if (this.edit) method = this.editTool;
    return method().then((response) => {
        this.$refs.dialogInfo.setSuccess(response);
      })
      .catch((error) => {
        this.$refs.dialogInfo.setError(error);
      })
      .finally(() => {
        this.$emit("completed");
      });
  }