AngularJs tip: Harness the power of parallel and sequential function calls that have interdependencies

service

(function () {
    'use strict';

    angular
        .module('app.user')
        .factory('myService', Service);

    Service.$inject = ['$http', 'API_ENDPOINT', '$q'];

    /* @ngInject */
    function Service($http, API_ENDPOINT, $q) {


        var getUserDetails = function (paramData) {
            return $q(function (resolve, reject) {
                $http.get(API_ENDPOINT.url + '/user/details', paramData).then(function (result) {
                    if (result.data.success) {
                        resolve(result.data);
                    } else {
                        reject(result.data.msg);
                    }
                });
            });
        };

        var getCountryDetails = function (paramData) {
            return $q(function (resolve, reject) {
                $http.get(API_ENDPOINT.url + '/country/details', paramData).then(function (result) {
                    if (result.data.success) {
                        resolve(result.data);
                    } else {
                        reject(result.data.msg);
                    }
                });
            });
        };


        return {
            getUserDetails: getUserDetails,
            getCountryDetails: getCountryDetails
        };
    }
})();

controller

(function () {
    'use strict';

angular
    .module('app.user')
    .controller('myService');

/* @ngInject */
function UserCtrl(userService,countryService) {
    var vm = this;

    vm.onCountryChange = function (id) {
        vm.states = vm.countries.filter(function (item) {
            return item.id === id;
        })[0].states;
    };

    function init() {

        var token = window.localStorage.getItem('TOKEN');
        vm.userData = jwt_decode(token);

        // fetch all country and its states parallelly
        myService.getCountryDetails()
            .then(function(msg){
                vm.countries = msg.data;
                // once both requests are completed, trigger onCountryChange()
                Promise.all([myService.getCountryDetails(), myService.getUserDetails(paramData)]).then(values => {
                  const countryDetails = values[0];
                  const userDetails = values[1];
                  vm.onCountryChange(userDetails.data.country.id);
                }).catch(error => console.log(error));
            },function(errMsg){
                console.log(errMsg)
            });

        var paramData = {
            params : {
                id : vm.userData.id
            }
        };

        // gets user data
        myService.getUserDetails(paramData)
            .then(function (msg) {
                vm.user = msg.data.map(function (obj) {
                    var rObj = {
                        name: obj.name,
                        email: obj.email,
                        country : obj.country.id,
                        state : obj.state.id
                    };
                    return rObj;
                })[0];       
            }, function (errMsg) {

            });
    }
    init();
}
})();

Here onCountryChange() seems to load earlier even before it gets the user country id, to optimise I can call two services in parallel to fetch data and once the request is completed and user object is set, onCountryChange(countryId) can be triggered to fetch all the states of the country to which user belongs.

Is it beneficial to make two parallel http requests?

How can I ensure that all requests are completed before calling the second function?

Answer №1

If you're faced with this scenario, here are two potential solutions:

Approach 1: Construct a chain of promises that involves invoking the getUserDetails function within myService.getCountryDetails.then. By doing so, the logic of getUserDetails remains unchanged.

Approach 2: Utilize Promise.all, which allows you to run both getCountryDetails and getUserDetails in parallel. This approach enables you to execute

vm.onCountryChange(vm.user.country.id)
at Promise.all(p1, p2).then, instead of within
myService.getUserDetails(paramData).then
.

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

Navigating the intricacies of retrieving network errors within an AngularJS application requires a deep

I've encountered the following code snippet in abcd.js: $http({url: 'some url' , method: 'POST', data: , headers: {} }).then(function(response)) { ............. }, function error(response) { .............. }) When an error occurs ...

What events precede and follow a keydown action in a Textarea field?

I need to prevent users from pressing function keys (F1, F2, etc.), the tab key, and any other characters from being added. The code below is supposed to achieve this on my website but it's not working. document.getElementById("code").addEventList ...

How to use Axios in Vue JS to access an array within a JSON object

Struggling to access arrays inside a JSON object and save them into separate arrays. Despite trying various methods, I have not been successful in retrieving these arrays. I suspect that my approach to accessing arrays within the JSON object is incorrect, ...

What could be the reason for receiving an undefined user ID when trying to pass it through my URL?

Currently, I am in the process of constructing a profile page and aiming to display authenticated user data on it. The API call functions correctly with the user's ID, and manually entering the ID into the URL on the front end also works. However, wh ...

How can I convert duplicate code into a function in JavaScript?

I have successfully bound values to a view in my code, but I am concerned about the duplicate nested forEach loops that are currently present. I anticipate that Sonarcube will flag this as redundant code. Can anyone advise me on how to refactor this to avo ...

Advancing the utilization of custom Angular input fields

I've developed a unique Angular input element that utilizes a textarea as its primary input field. Is there a way for me to pass along the enter key event to the main form? ...

Unable to apply programatically loaded attributes to the rangeslider.js plugin

I'm having trouble with my graph editor that uses the rangeslider.js plugin. The bars are not updating properly most of the time, and sometimes they don't work at all. I have a demo available here and a simplified version on Fiddle. Strangely, so ...

The parseJSON function is not compatible with AJAX requests

I am attempting to use ajax and retrieve JSON data in WordPress. Here is my Ajax code: $.ajax({ type: "POST", dataType : 'html', url: "/wp-content/themes/myproject/ajax/otros_alojamientos.php", da ...

The data remains stagnant even after employing the onDataChange function in react native following the integration of a reusable component

My reusable Text input component is not working properly for validation. I am unable to retrieve the input value as it always shows null. This is how I am retrieving the username and password: <LoginTextBox placeholderName='Email& ...

Sending a variable to an AngularJS factory

I am currently working on a select list that looks like this: <select name="make" class="form-control" ng-model="selectCity"> <option value="Kannur">Kannur</option> <option value="Agra">Agra</option> <option va ...

Troubleshooting issue with React mapping an array of items in a modal window

My state implementation is working perfectly fine, except for a minor issue with the modal window. Within the state, I have utilized objects that are normally displayed (you can refer to the screenshot here). Please pay attention to the "Open modal" butt ...

Using ReactJS to transform my unique array into an object before appending it to a list

Here is the array I am working with: [{…}] 0: {id: 2, createdAt: "2021-06-11T10:13:46.814Z", exchangedAt: "2021-06-11T08:04:11.415Z", imageUrl: "url", user: "user", …} 1: .... 2: .... 3: .... .... length: 5 __pro ...

Encountered an error in Pytorch LSTM conversion to ONNX.js: "Uncaught (in promise) Error: LSTM_4 node does not recognize input ''

I am attempting to execute a Pytorch LSTM network in the browser, but I am encountering the following error: graph.ts:313 Uncaught (in promise) Error: unrecognized input '' for node: LSTM_4 at t.buildGraph (graph.ts:313) at new t (graph.t ...

Accept only requests from my Chrome extension

I have successfully set up a NodeJS server with Express on DigitalOcean. My Chrome extension is able to make GET calls to the server without any issues. However, I am looking to enhance the security of the middleware below: // Add headers app.use(function ...

Efficiently organizing reducers into separate files in ReactJS and merging them together

My App is a simple counter app where buttons are images with their own counters. https://i.stack.imgur.com/qkjoi.png In my App.js file, I imported the reducer for the counters using the following code: import reducer from './reducers/reducerCounter&a ...

Issue with BCRYPTJS library: generating identical hashes for distinct passwords

After conducting a thorough search on Google, I couldn't find anyone else experiencing the same issue. The problem lies in the fact that no matter what password the user enters, the system returns the hashed value as if it is the correct password. Eve ...

Node.js and MongoDB Login Form Integration with Mongoose

I am relatively new to web development and currently working on a simple web page for user login authentication. My goal is to verify user credentials (username & password) on the LoginPage from a mongoose database, and if they are correct, redirect them t ...

The issue of the JQuery method failing to function properly on a button arises when the button is added

Upon loading a HTML page containing both HTML and JavaScript, the code is structured as shown below: <button id="test"> test button </button> <div id="result"></div> The accompanying script looks like this (with jQuery properly in ...

What is the significance of the "rc" within the version structure of an npm package?

Can someone help me understand what the rc in 2.2.0-rc.0 signifies? I'm curious if it indicates that this version is ready for production use. ...

Navigating through the meanjs framework's routes to access the server

I am currently working on implementing a new function in my controller called "matches.server.controller" named listTeams. I have included a new route in the matches.server.route.js file as shown below: 'use strict'; /** * Module dependencies. ...