0

I've found one issue while using Babel that I have not been able to resolve yet.

The thing is that I'm using promises within a class method and I need to access the this object of the class inside the promise to invoke class functions.

The code is

class SecurityService {
    constructor($q) {
        this.$q = $q;
    }

    isAuthenticated() {
        return true;
    }

    requestCurrentUser() {
        return this.$q.when({});
    }

    requireAuthenticatedUser() {
        let deferred = this.$q.defer();

        this.requestCurrentUser()
        .then(
          function (user) {
            if (this.isAuthenticated()) {
              this.$log.debug('Security: Access granted for user.');
              return deferred.resolve(user);
            }

            return deferred.reject();
          }
        );
    }
}

When I invoke requireAuthenticatedUser method it fails while executing this.isAuthenticated() because it is trying to find it in the promise scope.

Babel usually wraps the this variable in a upper scope variable, doing something like:

var _this4 = this;

to allow the use in the child scope, but it have checked that only does this thing when using callbacks, but not promises.

Is there any preset or any other thing that I need to import to make it work?

jesusbotella
  • 626
  • 4
  • 8
  • 1
    Depends on your target (i.e., ES5 or ES2015 or whatever), but you could use an arrow function, like `.then((user) => { if (this.isAuthenticated...` – Heretic Monkey Sep 27 '16 at 16:48
  • 1
    "*it only does this thing when using callbacks, but not promises.*" - no. It does that when you're using arrow functions, not plain functions. It has nothing to do with promises. – Bergi Sep 27 '16 at 18:16
  • 1
    Avoid the [deferrred antipattern](http://stackoverflow.com/q/23803743/1048572)! – Bergi Sep 27 '16 at 18:16
  • Thank you! After I posted the question I noticed that I wasn't using an arrow function :( Now it works great. I'll follow your advice about promises, thank you @Bergi – jesusbotella Sep 27 '16 at 18:37

1 Answers1

0

You can manually assign this to a variable before calling the method (the same way you're assigning $q.defer()).

requireAuthenticatedUser() {
  let deferred = this.$q.defer();
  var securityservice = this;

        this.requestCurrentUser()
        .then(
          function (user) {
            if (securityservice.isAuthenticated()) {
Evan
  • 456
  • 7
  • 16