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

What is the best way to prevent event propagation in d3 with TypeScript?

When working with JavaScript, I often use the following code to prevent event propagation when dragging something. var drag = d3.behavior.drag() .origin(function(d) { return d; }) .on('dragstart', function(e) { d3.event.sourceEvent ...

Encountering an HTTP parsing failure while sending XML through Angular 5's HttpClient

Struggling to access a local webservice through XML: Take a look at the code below: const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'text/xml', 'Accept': 'text/xml', 'Response- ...

Saving changes to mesh vertices in r67 of Three.js

I've encountered an issue with saving a mesh to a text file after manipulating vertices in my plane model. While the rendering on screen works as expected, the updates are not reflected in the saved file. Interestingly, if I move a vertex before the ...

Adjusting the sensitivity of mousewheel and trackpad using JavaScript

I am currently utilizing CSS3 to smoothly move a div up and down based on the direction of scrolling. By monitoring the mouse wheel event, I can detect when a user scrolls down and trigger a CSS3 transition to slide the div up. However, I am encountering a ...

Using jQuery and Flask-WTF to achieve live word count in a TextAreaField - a step-by-step guide!

I am interested in adding a real-time word count feature to a TextAreaField using jQuery. I found an example that I plan to use as the basis for my code: <html lang="en"> <head> <script src= "https://code.jquery.com/jquery ...

Developing a responsive form in AngularJS featuring hierarchical lists

In my AngularJS model, I have a structure like this: region = { 'substances': [ { 'id': 123, 'name': 'Hello', 'versions': ['A', 'B', 'C'] }, { 'id': 456, ...

Creating a Pre-authentication service for AWS Cognito using VueJS

Implementation of Pre-Authentication feature is needed in my VueJS application for the following tasks: Validation of ID/Refresh Token to check if it has expired. If the IdToken has expired, the ability to re-generate it using the Refresh Token or altern ...

Swapping out components or features within AngularJS

Is it possible to make my dependencies interchangeable in AngularJS? For example, if I have a service named myService stored within the module myDependency, how can I switch out myDependency with a new service without disrupting the main application? Shou ...

Error: Ajax unable to parse JSON - property 'name' does not exist in the object

When accessing my report.php file, it returns a json data. Here is the snippet of javascript code I am using to try and read the json: <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script> $(document).ready(function ...

Framework7 initialization not triggering when page is initialized

Unable to get init function working in my Framework 7 app. I have attempted all the solutions provided in the following link: Framework7 Page Init Event Not Firing // Setting up Application var myApp = new Framework7({ animateNavBackIcon: true, ...

Issue with DragControls in Three.js not detecting intersections

My current challenge involves setting up DragControls in my Three.js project. After researching online, I found that the process should be quite simple. The code I have written is as follows: let dragObjects = [obj] const dragControls = new DragControls(dr ...

Guide to generating a text string by utilizing the foreach loop

Is there a way to combine text strings from interfaces into a single file for display in UI? The current code is generating separate files for each interface. How can I achieve the expected result of having all interfaces in one file? Additionally, is it ...

The Ajax readyState consistently displaying a value of 0

I am encountering an issue with my Ajax code as it always returns 0 when I access 'readyState'. I have not been able to identify the source of the problem yet. Any assistance on this matter would be greatly appreciated: var xhr = null; function ...

encountering an unforeseen error during an ajax request

Currently, I am utilizing an ajax request in my Chrome extension to connect with an API and retrieve data. Initially, there were CORS errors which I managed to resolve. However, I am now encountering some ambiguous errors where the links are getting mixed ...

Failure to achieve success with jQuery Ajax

success in my AJAX call is not triggering at all, leaving me puzzled as to why. None of the alerts specified in the AJAX file are appearing. The form: <form onsubmit="check_reg();return false;" method="post" name="reg_form" id="reg"> <label ...

Randomizing the JSON loop on every page refresh

Having a JSON file containing various data items (as an example) that I am utilizing with handlebars.js to generate templates. The challenge lies in displaying 15 stories (each within their own div) on page load while shuffling their positions upon each r ...

Having trouble with the parent folder functionality in JavaScript?

I am facing a challenge with my website's structure as I have an old setup that needs to be updated. http://localhost/enc/pdfs/ : This directory contains some html files that are uploaded via ajax to be displayed on a tabbed div using: var Tabs ...

How can I retrieve an image from a library and automatically update the image in SharePoint every 30 seconds?

I have a web part and I have written the code below: However, it is only fetching one image. How can I fetch all images from the library and change the image every 30 seconds using JavaScript or jQuery? public class MSDN : System.Web.UI.WebControls.WebPa ...

What is the best way to clear an array?

Yesterday I had a query regarding JSON Check out this link for details: How to return an array from jQuery ajax success function and use it in a loop? One of the suggested answers included this script: setInterval(updateTimestamps,30000); var ids = new ...

Extract the list of selected item Id's from the HTML table and transfer them to the Controller

I have a table in my ASP.NET MVC project that displays information about file types and IDs (which are hidden) to the user. When the user selects checkboxes and clicks on the "Send Request Mail" button, I need to retrieve the IDs of the selected rows and ...