AngularJS service does not halt for the success function to complete

I am facing an issue with my service where the success function in the controller is not being executed immediately. The compiler is parsing the lines after the service call, which is not the desired behavior. In debug mode, I noticed that there is a delay of around 10 milliseconds before my data is available.

.factory('myService', ['$http', '$q', function($http, $q){
var deferObject,
    myMethods = {

        getDepartments: function(d) {
            console.log("Reached here");
            var allDepartments=[];
            var promise=$http.get("http://localhost:8087" + "/projects/"+d );
            var deferObject = deferObject || $q.defer();
            console.log("Reached here too");
            promise.then(

                // OnSuccess function
                function(answer){
                    console.log("Reached here as well");
                    // This code will only run if we have a successful promise.
                    deferObject.resolve(answer);
                            var setDepartments = new Set();

                            for (var i = 0; i < answer.data.length; i++) {
                                setDepartments.add(answer.data[i].department);

                            }

                            setDepartments.forEach(function (value) {
                                var department = {name: value};
                                allDepartments.push(department);

                            });
                    console.log(allDepartments);
                    return allDepartments;
                },
                // OnFailure function
                function(reason){
                    // This code will only run if we have a failed promise.
                    deferObject.reject(reason);
                });

            return allDepartments;
        },
        getData: function(d) {
            var promise=$http.get("http://localhost:8087" + "/projects/"+d )
             var deferObject = deferObject || $q.defer();

            promise.then(
                // OnSuccess function
                function(answer){

                    // This code will only run if we have a successful promise.
                    deferObject.resolve(answer);
                },
                // OnFailure function
                function(reason){
                    // This code will only run if we have a failed promise.
                    deferObject.reject(reason);
                });

            return deferObject.promise;
        }

    };

return myMethods;

}]);

Answer №1

My solution involved utilizing q.all to ensure that all requests were completed before proceeding with the program's execution.

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

Adding default parameters in AngularJS Route-UI is a useful feature for setting up

Using angular UI-Router in my app, I've set up my base language as English. I have both English and Hebrew locals, and I want to avoid adding parameters to the URL if the language is English. For instance: Home English --> http://example.com/ ...

The Material UI Elements are not displaying properly as expected. Instead of seeing the MUI elements, a tan box is appearing. What steps can I take to resolve this

I'm currently using Material UI to build a basic header, footer, and profile page. However, whenever I attempt to display any type of element (such as Menu, Appbar, Toolbar, IconButton, Tab, Tabs, etc.), the page only shows a tan box instead of the a ...

Resolving Cross-Browser Issues with jQuery CSS Positioning on Hover of Div Elements

Struggling to create a jQuery interface that is functional across all browsers, although the current version should work on most Windows browsers. Check it out here: (Please keep in mind that the problematic part is kept minimal and the solution is expec ...

Value binding with conditional rendering in VueJS 2

My goal is to utilize VueJS 2 to render an inline condition while simultaneously adding a value to a DOM element. I am aware that I can use v-if to control the visibility of elements based on conditions, but how can I achieve an inline condition? For exam ...

React callbacks involve the interaction between three different components

Currently, I am working with 3 distinct components: -The friendsPage component contains a list of friends and invitations to friends -The friendComponent displays detailed information about a friend along with possible actions (which are handled in the t ...

What methods are available for setting data to a field using CKEditor in a Protractor test?

Encountered an issue where I received a "element not visible" message in Protractor while attempting to input data into a field with CKEditor. This application is built with AngularJS. element(by.model("question.translations[lang.locale].answer")).sendKey ...

Manipulating CSS for a certain ID that is applied to multiple elements with the help of JQuery

I am attempting to conceal all div elements except the initial one within a specific ID. Despite my efforts to create a custom jQuery script, it does not appear to be functioning. $("div.hero-featureSwap:not(:first)").css({display:none}); Is this scr ...

Tips for spinning a gltf model as you scroll through the webpage

I am currently working on achieving a smooth rotation of a gltf model while scrolling. I have successfully developed a function that converts pageYOffset from pixels to radians let scrollPositionRad = 0; window.addEventListener("scroll", onWindowScroll ...

The ngOnChanges lifecycle hook is triggered only once upon initial rendering

While working with @Input() data coming from the parent component, I am utilizing ngOnChanges to detect any changes. However, it seems that the method only triggers once. Even though the current value is updated, the previous value remains undefined. Below ...

Can the image quality be improved gradually while zooming in on Safari Mobile?

Are there any JavaScript or jQuery plugins available that can improve the quality of large images when zooming, similar to Google Earth or Maps? I'm looking for a solution that works well in mobile browsers, but a desktop version would also be accept ...

The amazing property of AngularJS - Scope

I have saved this HTML code in a file. Here is the HTML : <!-- checkbox 1 --> <input type="checkbox" name="checkbox1" id="checkbox-group1" ng-model="checkbox1" value="group1"> <input type="checkbox" name="checkbox1" id="checkbox-group2" ng ...

Load various types of classes and run functions with matching names

I have encountered a challenging issue that needs to be resolved. Imagine having multiple classes located in a directory named services. These classes all include a constructor() and send() method. Examples of such classes can be Discord, Slack, SMS, etc. ...

Continuously simulate mousewheel events

I'm trying to make my mousewheel event trigger every time I scroll up, but it's only firing once. Can you assist me with this issue? Please review the code snippet below. $('#foo').bind('mousewheel', function(e){ if(e.o ...

Refresh the Angular view only when there are changes to the object's properties

I have a situation where I am fetching data every 15 seconds from my web API in my Angular application. This continuous polling is causing the Angular Material expansion panel to reset to its default position, resulting in a slow website performance and in ...

Organize an array of objects in JavaScript into a structure with nested children

I am facing a challenge with organizing an array of objects based on parentId and sort values. I need to create a nested array with 'children' and ensure proper sorting. Consider the following data: [{ id: 1, sort: 2, parentId: null ...

When utilizing the getIntersectionList function, IE 9 may experience a malfunction and cease functioning

I am currently working with SVG code and JavaScript, trying to achieve a specific intersection result. <svg id="svgSurface" width="500" height="500"> <defs> <marker id="Triangle" viewBox="0 0 20 20" refX="0" refY="0" markerUnits ...

Unable to view through transparent merged geometry in three.js

Could someone assist me in understanding why, when merging the geometries of these boxes, I am encountering visibility issues from certain angles? Blue boxes represent normal individual boxes, while Orange boxes are the result of merged geometries. I am u ...

Switching a Rails/Ajax form from create to update mode upon submission

While experimenting with a star ratings page, I encountered an issue where the form element remained in "Create" mode instead of updating to an "Update" method after submission. The rating form is ajaxified, but it lacks the functionality to dynamically sw ...

Ways to implement bootstrap Modal on a different HTML page

Does anyone know the best way to utilize the Bootstrap modal in a separate HTML page that is generated within the initial HTML page? ...

Can JavaScript and CSS be used to dynamically style textarea content as it is being typed by the user?

I am wondering if it is possible to apply styling to content in a textarea as a user inputs text. For instance: <textarea>abcdefghijklmnopqrstuvwxyz</textarea> Is there a way to highlight all the vowels in the textarea string above using jav ...