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

Encountering a tucked-away issue with the Safari scroll bar?

Encountered an interesting bug where users are unable to scroll down a text nested inside a div. This issue seems to be isolated to Safari, as it doesn't occur in other browsers. I have prepared a sample file to demonstrate the bug and would apprecia ...

The v-autocomplete feature in vuetify doesn't allow for editing the text input after an option has been selected

Link to code on CodePen: CodePen Link When you visit the provided page and enter "joe" into the search box, choose one of the two Joes that appear. Try to then select text in the search box or use backspace to delete only the last character. You will no ...

Struggling to understand JSON in joint.js?

I am trying to utilize the joint.js library to render a JSON data as a chart... let paper = new joint.dia.Paper({ el: $('#paper'), width: 600, height: 200, model: graph }); let graph = new joint.dia.Graph; let json = '{"em ...

change the css back to its original state when a key is pressed

Is there a way to retrieve the original CSS of an element that changes on hover without rewriting it all? Below is my code: $(document).keydown(function(e) { if (e.keyCode == 27) { $(NBSmegamenu).css('display', 'none');} ...

My current array is arr=[1,2,3,4]. I recently added an element to it using arr.push(5). Now I want to rearrange the array to be [5,4,3,2,1]. Any suggestions on how to achieve this

I currently have an array in the following format: var arr = [1,2,3,4] // Add another element to the array arr.push(5) // Now, arr = [1,2,3,4,5] I want to print my array as The elements in the array arr are: 5,1,2,3,4 When I use Arr.reverse(), it retu ...

Displaying interactive charts in a pop-up window using Highcharts within a Bootstrap

I am looking to display a highchart inside a popover. Check out my code in this jsfiddle http://jsfiddle.net/hfiddle/abpvnys5/47/. Here is the HTML: <ul class="stat_list" style="float: left;"> <a data-toggle="popover" data-trigger="hover ...

Attempting to bring in an image file into a React component

My attempt to add an image at the top of my file failed, so I am looking for help with importing it. The code I originally tried did not work. The image does not display using the code below <img src={require('../../blogPostImages/' + post.bl ...

Unable to view HTML without an internet connection

I have encountered an issue where my files work fine when uploaded to an online server, but do not work when accessed locally offline. An error message about a cross-origin issue appears. How can I solve this problem? Error message: Security Error: Conte ...

Jquery double-click Event Not Functioning Properly

I've been attempting to toggle the visibility of my footer navbar while also changing the chevron icon. When the navbar is hidden, I want the chevron pointing up to be displayed, and when the navbar is shown, I want the chevron pointing down to be dis ...

Creating a mongoose schema that contains an array of objects and linking it to ng-model

As a beginner in coding, I appreciate your patience with me if the information provided isn't perfectly clear. I'm giving it my best shot. Let's dive into the issue. { email: 'asdf', password: 'asdf', userl ...

Any suggestions on how to repair this Node.js login interface?

Currently grappling with setting up a Node.js application with a MySQL database to create a basic login functionality. Encountering an issue: Cannot POST /login <body class="hero-image"> <div id="container"> <div ...

Unable to retrieve information from the wiki API

Here is the link to my codepen project: https://codepen.io/mlestina/pen/OZpOQW?editors=1111 I am having trouble retrieving data from the Wiki API. When I check the Contr-Shift-J readout, I see: Loading failed for the <script> with source “https: ...

Guide to handling multiple forms within a single template using Express

If I have an index.html file containing two tables - "Customers" and "Items", along with two forms labeled "Add customer" and "Add item", how can I ensure that submitting these forms results in a new entry being added to the respective table as well as t ...

Unable to generate onsen-ui popover

My expertise lies in utilizing the Monaca platform for developing mobile applications using Onsen UI and AngularJS. I am looking to incorporate a popover feature from Onsen into my app, and have tried the following code snippet: angular.module('app& ...

Analyzing CSS transform values for rotate3d utilizing regular expressions

I want to split css transform values into an array, while keeping rotate values grouped together. For instance: 'translate3d(20px, 5px, 10px) rotateX(20deg) rotateY(10deg) rotateZ(0deg) skew3d(20deg, 10deg) rotateX(-20deg) rotateY(100deg) rotateZ(-3 ...

Updating the CSS style of an inner DIV using JavaScript

Can you provide guidance on how to modify the background color using JavaScript for the different styles listed below? i) Internal Style sheet and/or ii) External Style sheet I am currently working with the card deck slide show available at https://githu ...

Is there a way to automatically zoom in when clicking on a marker and centering the map to that

I have integrated a map into my project where I am currently plotting random coordinates. These coordinates are stored in a data table and everything is functioning smoothly. However, I am facing an issue with implementing a zoom feature using the panTo m ...

Having trouble getting the templateUrl to work properly with AngularUI-Router?

Can you please explain the flow of how a URL is processed when visited and provide insights on why Angular's templateUrl may not be working? When a user clicks on a URL in their browser, it first checks the cache to see if the URL is saved from the $ ...

Submitting data from a JavaScript frontend to a PHP backend

I've exhausted all options in attempting to resolve this issue. The javascript code is designed to send a list of product IDs to a PHP page. When products are selected, the submit button should activate the submit function. function submit() { ...

When a string begins with the "<" character, jQuery regex is unable to find a match

I am attempting to check if a string starts with the "<" character, but I am running into issues. The expression works perfectly fine on regex101.com, however, it fails when used in my personal files. When I input a backslash everything works as expect ...