While utilizing Babel, I encountered a problem that I have not yet been able to solve.
The issue arises when I use promises within a class method and I require access to the this object of the class inside the promise in order to call class functions.
Here is the code snippet:
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 calling the requireAuthenticatedUser method, it fails while executing this.isAuthenticated() because it is searching for it in the promise scope.
Babel typically encapsulates the this variable in an upper-scope variable, such as:
var _this4 = this;
This allows its usage in the child scope, but I have noticed that it only does this with callbacks, not promises.
Is there a specific preset or any other import required to make this functionality work?