Hoppe
Hoppe

Reputation: 6815

Possible to rewrite this so that I don't have to assign this to a variable when using promises

We have run into some issues with TypeScript and this. Is it possible to rewrite the callbacks below without assigning this to that?

Within my namespace, in the same file as this component, I have an enum:

enum ToggleStates {
  State1 = 1,
  State2,
  State3
}

Then in a function in the same component:

  let that = this;

  defer.then(function(response) {
      if (response.success !== null) { // if there is a success handler
        that.$rootScope.$broadcast("w-signed", this.toggleStates, this.currentSigned);
      }else {
        that.$rootScope.addAlert("danger", error);
      }
  }).catch(function(response) {
      that.$rootScope.addAlert("danger", error);
  }).finally(function() {
      that.$rootScope.addAlert("danger", error);
  });

For a similar problem, we used lambdas to get around the issue. I tried the following:

  defer.then = (response) => {
      if (response.success !== null) { // if there is a success handler
        this.$rootScope.$broadcast("w-signed", this.toggleStates, this.currentSigned);
      }else {
        this.$rootScope.addAlert("danger", error);
      }
  }

  defer.catch = (response) => {
       this.$rootScope.addAlert("danger", error);
  }

  defer.finally = () => {
    this.$rootScope.addAlert("danger", error);
  }    

But then I get the following error:

wp-leftnavcomponent.ts(208,65): error TS2339: Property 'toggleStates' does not exist on type 'WpListComponentController'.

Upvotes: 1

Views: 33

Answers (1)

Joe Clay
Joe Clay

Reputation: 35817

You're overwriting then/catch/finally with the lambdas instead of passing them in. The only bit you need to replace in your original example is function () { } with () => {}.

defer.then((response) => {
    if (response.success !== null) { // if there is a success handler
        this.$rootScope.$broadcast("w-signed", this.toggleStates, this.currentSigned);
    }
    else {
        this.$rootScope.addAlert("danger", error);
    }
})
.catch((response) => {
    this.$rootScope.addAlert("danger", error);
})
.finally(() => {
    this.$rootScope.addAlert("danger", error);
});

Upvotes: 1

Related Questions