"Utilizing Promises in AngularJS Factories for Synchronous API Calls

Attempting to implement synchronous calls using a factory pattern.

$scope.doLogin = function (username, password, rememberme) {
        appKeyService.makeCall().then(function (data) {
//            data = JSON.stringify(data);
            debugAlert("login controller app key service"+data);
            var appkeyvalue = data.d.appkey;
            sessionConfigurationService.setBasicToken(appkeyvalue);

            loginService.makeCall(username, password, rememberme).then(function (accessTokenData) {
                if (accessTokenData.access_token !== "")
                {
                    sessionConfigurationService.setAccessTokenData(accessTokenData.access_token);
                    userPreferencesService.makeCall().then(function (userPreferencesData) {
                        if (userPreferencesData.d.userId !== "")
                        { 
                            sessionConfigurationService.setUserPreferences(userPreferencesData.d);
//                            $window.location.href = '/base.html';
                        }
                    });
                }
            });
        });
    };

The appKeyService factory is

app.factory('appKeyService', function ($q, authenticatedServiceFactory, configurationService) {
    var deffered = $q.defer();
    var service = {};

    service.makeCall = function () {
        debugAlert("appKeyService async method request start");
         authenticatedServiceFactory.makeCall("GET", configurationService.getAppKeyURL(), "", "").then(function (data) {
            debugAlert("appKeyService async method response")
            deffered.resolve(data);
        });
        return deffered.promise;
    };
    return service;
});

The authenticated service factory is

app.factory('authenticatedServiceFactory', function ($http, $q, sessionConfigurationService) {
    var deffered = $q.defer();
    var service = {};
    service.makeCall = function (methodType, URL, data, authType) {

        var headerValue = "";
        if (authType === "Basic") {
            headerValue = sessionConfigurationService.getBasicToken();
        } else if (authType === "Bearer") {
            headerValue = sessionConfigurationService.getBearerToken();
        }

        var config = {headers: {
                'Authorization': headerValue,
                'Accept': 'application/json;odata=verbose',
            },
            withCredentials: true,
            async: false
        };
        if (methodType === "GET") {
            $http.get(URL, data, config)
                    .then(function (getData) {
                        debugAlert("GET method response" + JSON.stringify(getData));
                        deffered.resolve(getData.data);
                    }, function (error) {
                        debugAlert("GET method response error" + JSON.stringify(error));
                        deffered.reject(error);
                    });
        }
        ...
        return deffered.promise;
    };
    return service;
});

However, it seems that the service calls are not executed synchronously. The "then" part in the controller does not execute after receiving the response but instead executes one after the other. How can I resolve this issue?

Answer №1

@Frane Poljak

Hey there! Appreciate your input. I recently made some adjustments to the code snippet below:

var promise = $q.defer();

I relocated the variable declaration inside the makeCall function and now it's functioning as intended. Thanks for your assistance!

app.factory('appKeyService', function ($q, authenticatedServiceFactory, configurationService) {
    var service = {};

    service.makeCall = function () {
    var promise = $q.defer();

        debugAlert("appKeyService async method request start");
         authenticatedServiceFactory.makeCall("GET", configurationService.getAppKeyURL(), "", "").then(function (data) {
            debugAlert("appKeyService async method response")
            promise.resolve(data);
        });
        return promise.promise;
    };
    return service;
});

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

Combining various array values into a single key in JSON格式

Issue: I am working on a sign-up form for new users using HTML. The goal is to store multiple arrays (each containing "username: username, password: password, topScore: 0) within one JSON key ("user" key). However, the current functionality only allows f ...

Combine JavaScript array objects based on their unique IDs

Looking to combine 2 arrays of objects based on IDs (ID and AUTOMOBIL). However, the current code only saves the last array of objects (OPREMA). Any suggestions on how to merge all of them correctly? If the ID in a1 is == 1, I want to save all OPREMA wher ...

Transfer the values selected from checkboxes into an HTML input field

I am attempting to capture the values of checkboxes and then insert them into an input field once they have been checked. Using JavaScript, I have managed to show these values in a <span> tag successfully. However, when trying to do the same within a ...

Navigating to redirected URL within jquery's get() function

When I tried sending a get request to a Google App Script URL in my application using JQuery's get method, everything was working fine. However, out of the blue, that API started redirecting to a different URL in case of an authentication error. As a ...

Halt and anticipate a boolean reply from another function

Is there a way to create two functions in JavaScript, run one of them, then within that function, execute the other and pause until it receives a response (yes or no) before moving on to an if statement? The user's response should be manual. Here is ...

Creating seamless compatibility between the elliptic library in JavaScript and the ecdsa library in Golang for efficient cross-platform operations

I am having issues with validating a signature created using the elliptic JavaScript library and the ecdsa library from Golang. The elliptic curve in question is secp256k1. Below are some snippets of code: Here are the TypeScript utility functions: impor ...

Extending the href value using jQuery at the end

Can someone help me with this link: <a id="Link" href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2745425453424b4b524940674e0a4355464e4909494253">[email protected]</a>?subject=I-Drain Bestellung& ...

What are some effective ways to address conflicts between select2 versions 3.5 and 4.0?

Although not identical, the issue outlined in this discussion thread - https://wordpress.org/support/topic/select2-conflicting-with-acf-v5 resonates with my current predicament. In the scenario of a WordPress website with two plugins, one employing select ...

Exploring custom JavaScript with Construct 2's generated code

How can I access the score of a game user in Construct2 Engine using external JavaScript? Is there a method to achieve this? Appreciate any guidance on this matter. ...

Is it possible to perform cross domain AJAX calls while implementing Basic Authentication?

Having a ColdFusion application located behind an ISA Server presents some challenges. In this case, part of the application requires Basic Authentication while another part does not. The issue arises when trying to access cookies set by the ISA Server upo ...

Restarting a JavaScript function upon switching views in Vue.js

I am new to working with Vue.js and I have a Laravel app that utilizes it. One issue I am facing is that when the homepage is loading, all elements like owl carousel and rev slider are initialized. However, if I navigate to other routes such as contact or ...

Encountering problems when attempting to effectively filter a list of products using data

<div id="prod"> <div class="content" data-brand="Andrew" data-price="1000" data-store="JCPenny">Andrew</div><br /> <div class="content" data-brand="Hill" d ...

What is the correct way to change the v-model value of a child component within a parent component

Currently, I am in the process of mastering Vue.js and I have a specific goal. I want to modify the binding value of the child component's v-model and then trigger an event in the parent component. As I delve into the Element UI documentation, I aim ...

Modifications to the selected input do not impact the current state of the model

Declare 3 select inputs with hierarchical data to be chosen: <select data-ng-model="current.manufacturer" data-ng-options="c.name for c in manufactures"></select> <select data-ng-model="current.mark" data-ng-options="c.name for c in current ...

Here is a guide on how to develop a PHP function that interacts with a textarea to display text in the specified color by using syntax like [color:red]

Is it possible to code a PHP function that can work alongside a textarea to display text in the specified color by using a syntax like [color:red]? This function operates in a similar manner to Facebook's @[profile_id:0] feature. ...

Exploring ES6 classes in Java Script: accessing prototype properties

After searching extensively for an answer and coming up empty-handed, I decided to pose my question here. When creating an object constructor in JavaScript as shown below: function Car(speed){ this.speed = speed; this.position = 0; } Car.prototype.m ...

Does it have .hasOwnProperty and a significant value?

Today, I encountered a tricky situation involving the JavaScript Object.hasOwnProperty method. I was working on a form that creates properties on an object. The issue arose when dealing with a select box that had a value selected and then reset back to it ...

Automatically adjust multiple images on an HTML webpage

Just starting out with html programming here. Looking to add top margin using a span class, any tips on how to tackle this issue? ...

Tips for creating JavaScript event handlers for Laravel forms

Looking to create a form for my Laravel application that includes text input boxes, radio buttons, and optional values. Here is the basic structure of the form: <html> <head> <title>Form Generation</title> <body> <form act ...

What is the best way to use element.appendChild to generate a link?

I am currently utilizing the following snippet of Javascript to extract information from the current webpage using a browser extension. I have only included a portion of the code that is relevant, as the full script is quite lengthy. The code works perfect ...