"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

Tips on locating information within a pre-existing GET array with parameters provided

Apologies for the unclear title. I am currently utilizing a category chooser that pulls categories from an API. The process involves fetching a list of categories, filtering out their names, and presenting them in the category chooser. Upon clicking submit ...

Storing data on the server for your Cocos2d JavaScript game

I've been struggling with implementing a savegame option for my cocos2d JavaScript game. After following a tutorial from Ray Wenderlich (thanks, Ray!), I gave up on trying to do it client-side and am now looking into saving XML files to a web server w ...

Incorporate the xml2js JavaScript library with Angular 2 for enhanced functionality

I've been attempting to utilize xml2js as an XML parser within my Angular 2 (RC 1 with TypeScript) web application. Unfortunately, I've encountered several errors without finding a solution that works. Here is the detailed process I followed: ...

How can I incorporate multiple states into a conditional statement in ReactJS?

Is there a more efficient way to achieve this task? I'm struggling to come up with a cleaner solution as the current approach looks messy. I need to check multiple states in an if statement and the only method I can think of right now is the one prese ...

Utilizing VueJS and Lodash: The technique for extracting an array of objects exclusively featuring a specific key string

I am attempting to extract certain data from an Object that has a string _new attached to it. Explore the code on Codesandbox: https://codesandbox.io/s/vibrant-bardeen-77so1u?file=/src/components/Lodash.vue:0-353 This is what my data looks like: data.j ...

Ways to retrieve all elements based on their class names?

What is the equivalent of using $('.class') in JQuery to get all elements by class name with pure JavaScript? ...

Form submission requires a checkbox to be checked

I have been searching for a way to make checkboxes required. Is there a method similar to using required="required"? Currently, I generate my checkboxes in the following manner and would really appreciate any guidance on this topic. It's crucial for m ...

What is the best way to trigger an AngularJS function after a row selection event in Django?

In order to display the selected row id when a row selection event takes place in the datatable worklist, I am attempting to achieve this using an AngularJS function shown below: function showSelectedRowId($scope){ var dtWorklist = datatable_work ...

Is there a way to trigger an Angular $scope function from a hyperlink in the current or a new tab using a right

Here is the HTML code I am working with: <a href="" ng-click='redirectToEntity("B-",obj.id")'>Click me and Process function and then redirect</a> While this code successfully processes the function and redirects to the desired page ...

Is there a way to verify if the JSON Object array contains a specific value or not?

Hi there! I'm new to JavaScript and I have a question. I need to determine whether the value of an Object is included in a JSON file or not. If it is, then I need to do one thing, otherwise I need to do something else. First, I am retrieving the JSON ...

Tips for adjusting column sizes in ag-grid

I'm a beginner with ag-grid and need some help. In the screenshot provided, I have 4 columns initially. However, once I remove column 3 (test3), there is empty space on the right indicating that a column is missing. How can I make sure that when a col ...

The absence of localStorage is causing an error: ReferenceError - localStorage is not defined within the Utils directory in nextjs

I've been trying to encrypt my localstorage data, and although it successfully encrypts, I'm encountering an error. Here's the code snippet (./src/utils/secureLocalStorage.js): import SecureStorage from 'secure-web-storage' import ...

Display PDF blob in browser using an aesthetically pleasing URL in JavaScript

Using Node, I am retrieving a PDF from the server and sending it to my React frontend. My goal is to display the PDF in the browser within a new tab. The functionality works well, but the URL of the new tab containing the PDF is not ideal. Currently, the U ...

Keep the sub-menu in a kendo context menu from closing until the user either hovers over another menu item or clicks outside of the current item

Please take a look at this example: Due to the small size of sub-items, the sub-menu closes quickly when hovering over the menu and losing focus. My goal is to keep an opened sub-menu from closing until the user hovers over another menu item or clicks on ...

Having difficulty implementing conditional coding within an ng-repeat directive and facing challenges while trying to make

After spending years working in Classic ASP with VBScript, I recently took the leap into the AngularJS world along with JQuery and Ajax. The transition has been incredibly exciting for me. I am particularly drawn to Angular due to its ng-repeat feature, wh ...

Looking for a comprehensive calculation that takes into account various input values?

I need to display the List Price at the bottom of the form so users are aware of the cost to list their item. Within a php file, I have defined price brackets. For example, if the listing price is £150.00, it falls between £100 and £199.99 and thus nee ...

Is it possible to determine the number of JSON properties without the need for a loop?

I have a question about organizing data. I have a vast amount of data with various properties, and I am looking for a way to display each property along with how many times it occurs. For example: 0:[ variants:{ "color":"blue" "size":"3" } ] 1 ...

Enhancing Angular Directives with Dynamic Templates upon Data Loading

I am facing an issue with a directive that is receiving data from an api call. While the directive itself functions properly, the problem seems to be occurring because the directive loads before the api call is complete. As a result, instead of the expecte ...

"Can you share how to send an array of integers from a Jade URL to an Express.js route

I am currently working on creating an array of integers in JavaScript using the Jade template engine. My goal is to send this array to an Express.js route when a button is clicked. I have attempted the following code: Jade File: //Passing the ID to fu ...

Having issues with IE8 and SmoothGallery script errors

I'm currently utilizing the SmoothGallery plugin created by Jon Designs to enhance the website of one of my clients. However, there seems to be a minor issue in Internet Explorer 8 when attempting to navigate to the next image. Interestingly enough, a ...