Leveraging this within the realm of promises utilizing babel

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?

Answer №1

To ensure proper execution, it is recommended to assign the value of this to a variable before calling the method, similar to how you are assigning $q.defer().

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

        this.requestCurrentUser()
        .then(
          function (user) {
            if (securityservice.isAuthenticated()) {

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize ng-bootstrap in an Angular CLI project by integrating it with npm commands

I've been attempting to set up a project using Angular CLI with ng-bootstrap, but I'm having trouble getting the style to work properly. Here are the exact steps I followed (as outlined in the get-started page): Create a new project using `ng n ...

Listen for the load event during an AJAX request without using jQuery's add

I have four HTML files and four corresponding JavaScript files. Each JavaScript file is externally loaded by its respective HTML file. Specifically, index.html loads javascript.js, 1.html loads javascript1.js, 2.html loads javascript2.js, and 3.html loads ...

What is the best way to save Vue state in a cookie while transitioning between form steps in a Laravel application

Imagine a scenario where a user is filling out a multi-step form, and we want to ensure that their progress is saved in case they lose connection. This way, the user's data will not be lost between different form steps. In addition to saving each ste ...

Tips for creating a new route within a separate component in React JS without causing the previous one to unmount

I am currently developing a recipe website using React JS and React Router. On the HomePage, I have set up a display of cards, each representing a preview of a recipe. Each card is enclosed within a <Link></link> tag. When one of these cards ...

Refresh in AJAX, automated loading for seamless transition to a different page

Having an issue with the page not auto-refreshing, although it loads when I manually refresh. P.S Loading the page onto another page. Below is my HTML and AJAX code along with its database: The Trigger Button <?php $data = mysqli_query ...

Adjusting the viewer.js script

In order to view my pdf files using Mozilla's pdfjs plugin, I currently pass a query parameter to viewer.html like this: http://localhost/MyProject/viewer.html/?file=file.pdf Although this method works fine for me, I have a unique requirement for my ...

Filtering Array Elements with AngularJS Repeater

Can I customize my ng-repeat to filter through an array or object? Currently, I am populating via an http request like this: <div class="ibox" ng-repeat="data in appraisals track by $index"> However, I am wondering if there is a way to apply a fi ...

How big is the array size in the WebAudio API data?

Exploring the visualization of waveform and FFT generated by the audio stream from the microphone through the WebAudio API. Curiosity strikes - what is the size of each data array available at a given moment? Delving into the getByteTimeDomainData, it men ...

When utilizing ng2-bootstrap, there is no directive that is defined with the "exportAs" attribute set to "bs-modal"

I found a tutorial that I am trying to emulate from this website However, when I insert the template into my HTML file <div class="modal fade" bsModal #staticModal="bs-modal" [config]="{backdrop: 'static'}" tabindex="-1" role="dialog" ...

Auth0 Angular - No routes found to match

I recently set up an angular application and integrated it with Auth0 by following two helpful tutorials: https://auth0.com/docs/quickstart/spa/angular2/01-login https://auth0.com/docs/quickstart/spa/angular2/02-calling-an-api Here is a brief overview o ...

Changing the CSS property from "display: none" to "display: block" using JavaScript causes all the div elements to overlap

My issue involves several radio inputs where clicking one should reveal a hidden div containing information. However, when this div appears, it overlaps with the footer instead of staying positioned between the footer and radio input as intended. I am str ...

Contrast between utilizing filter_input and accessing $_POST directly following an asynchronous AJAX request

When I use filter_input(INPUT_POST, 'attribute') and $_POST['attribute'], I get different results and I can't figure out why. The Post-Request is sent by a JavaScript script built with JQuery and it looks like this: // type javaS ...

Incorporating Distinct Items into an Array with JavaScript

There is a Filter object that stores information about different Car Types. The data is fetched via AJAX calls - on the first call, objects 0-10 are created and added to an array. Subsequent calls bring more car types which are also appended to the array. ...

Sharing Codenvy developer environments for collaborative coding on StackOverflow

I wanted to test embedding a Codenvy Developer Environment in my Stack Overflow post. Here's the code snippet I used: <iframe name="factory-iframe" width="100%" height="600px" src="http://ide3.cf.codenvy-stg.com/factory?v=1.2&vcs=git&vcsurl=http%3 ...

Adding a Resource Bundle to a Vue project

I am looking to integrate the ResourceBundle package into my Vue project. After installing it with the following command: npm install resource-bundle I discovered these exported functions in the index.js file of the ResourceBundle package: export functi ...

Leveraging deep linking to launch the email application in react native

I am currently exploring the deeplink URL for the mail app on iOS. A scenario I have set up involves displaying an alert that, when the user clicks 'ok', redirects them to the default mail app. const openEmailApp = () => { if (Platform.OS ...

What could be the reason that step 3 of the AngularJS Tutorial is not functioning correctly?

During Step 3 of the AngularJS Tutorial, an additional e2e test is recommended to enhance the example: it('should display the current filter value within an element with id "status"', function() { expect(element('#status').text() ...

What is the preferred method for implementing a dynamic select control with Ajax

I'm having an issue with AJAX and MySQL in PHP. Can anyone offer assistance? Within my form, I have a select control: <form action="index.php" method="post" name="pretraga" class="border"> <p>Location:</p> <div ...

Having difficulty adding a custom library from a repository into an Ember project as a dependency

I've been working on a WebGL library that I want to include as a dependency in an EmberJS project. It seems like I should be able to do this directly from the repository without creating an npm package, but I'm running into some issues. To illus ...

Tips for utilizing identical properties across numerous styled elements:

Utilizing the styled-components library, I have enhanced the header components from the Blueprintjs library. The current template for the H6 component appears as follows: export const DH6 = styled(H6)` color: ${(props) => (props.white ? "white&qu ...