"Patience is key when it comes to waiting for an HTTP response

Looking for a solution in AngularJS, I have a service that calls the backend to get some data. Here is how the service looks:

app.factory('myService', ['$http', '$window', '$rootScope', function ($http, $window, $rootScope) {

return {
    GetTypeName(typeID, callback) {
        $http.get(backend_url + 'type/getById/' + typeID)
            .success(function (response, status, headers, config) {

                if (status === 200) {
                    callback(true, response);
                } else {
                    callback(false);
                }
            })
            .error(function (data, status, headers, config) {
                callback(false);
            });
    }
}   }]);

Now, I am trying to call this service from a controller like so:

getFormationsType = function(){
 for (i = 0; i != array.length; i++){
     myService.GetTypeName(typeID, function (result, data) {
         if(result){
             console.log(data.name);
             // do something with data.name here, and also need it outside of this func
         } else{
             console.log("error");
         }
     });
 }}

The issue I am facing is that the service does not wait for the result before moving on to the next lines of code. It jumps out of the getFormationsType() function and continues executing other tasks without waiting for the result. I need the result immediately after calling the service. How can I make the service wait for the result before continuing?

Your assistance is greatly appreciated.

Answer №1

In order to work with AngularJS, you need to use promises implemented by $q. This means that you cannot utilize ES6 promises or async/await. However, you can achieve your desired functionality using $q in the following way:

Start by modifying your service to return a promise instance:

app.factory('myService', ['$http', '$window', '$rootScope', '$q', function ($http, $window, $rootScope, $q) {

    return {
        getTypeName(typeID) {
            var deferred = $q.defer();
            $http.get(backend_url + 'type/getById/' + typeID)
                .success(function (response, status, headers, config) {

                    if (status === 200) {
                        deferred.resolve({ success: true, data: response });
                    } else {
                        deferred.resolve({ success: false });
                    }
                })
                .error(function (data, status, headers, config) {
                    deferred.resolve({ success: false });
                });
            return deferred.promise;
        }
    }
}]);

Then, within your controller, invoke your service recursively like this:

angular.controller('myController', ['myService', function (myService) {
    var array = [/* initialize your type ID array here */];
    var index = 0;
    function getFormationsType () {
        myService.getTypeName(this.array[this.index])
            .then(result => {
                console.log(result);
                if (this.index < this.array.length) {
                    this.index += 1;
                    getFormationsType();
                }
            })
            .catch(error => {
                console.error(error);
            });
    }
}]);

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

How can I use a button to save all changes made in a JqGrid checkbox column simultaneously?

In my jqgrid, there is a column named 'asistencia' which displays data from a database as checkboxes. These checkboxes are pre-checked based on the property formatoptions: {disabled : false}. I would like to implement a 'save' button th ...

I'm confused by the function: "sort((a: Article, b: Article) => b.votes - a.votes);"

I'm having trouble grasping the concept of the return statement in sortedArticles(). Can anyone provide me with a resource or explain how this sorting function works? sortedArticles(): Article[] { return this.articles.sort((a: Article, b: Article ...

What is the most effective way to retrieve specific data from this object using JavaScript?

I attempted to retrieve the number of hashtags used at a specific time using the Twitter API and an npm module called hashtag-count. Below is the program and the generated results object: var HashtagCount = require("hashtag-count") require('dotenv&ap ...

Experience real-time updates on webpages with Node.js and Socket.io

Seeking to integrate real-time push notification updates from a node.js server to the browser client. Explored socket.io at http://socket.io/docs/rooms-and-namespaces/ The business requirement involves users viewing a page with customer information and o ...

What is the method to establish a reference based on a value in programming?

Having some trouble setting the 'ref' of a TextInput from a value. Here's an example: var testtest = 'testvalue' <TextInput ref=testtest autoCapitalize="none" autoCorrect={false} autoFocus={false} placeholderTextColor="#b8b8b ...

Import ES6 code by wrapping it in parentheses

Currently delving into React Native and I'm intrigued by the parentheses used in the first line of import. import React, { Component } from 'react'; import { AppRegistry, Text } from 'react-native'; class HelloWorldApp extends Co ...

Utilizing JQuery to alter the text color if validation fails when entering a value

Is there a way to change the text in the input box to red when PHP validation fails using JQuery? I had success with Javascript, but it kept disappearing every time I clicked submit... <form class="link-form" method="post" action=""> <la ...

The JavaScript function is not being activated by clicking on Selenium in Chrome

Take a look at the HTML snippet below: <table class="table-main "> <thead> <tbody> <!----> <tr class="" ng-if="mapCtrl.isAdded" style=""> <td/> <td> <td> <t ...

What methods can be used to disable a JavaScript function, such as utilizing hasClass()?

I am currently customizing a WordPress theme to load posts and pages using AJAX. I have successfully implemented this functionality with the code snippet below, but now I need to prevent the AJAX function from running when clicking on the logo that links t ...

How to access form elements within a submit function without specifically defining the form name

I have a form that I am submitting using a submit function. However, instead of using document id for submission variable, I am utilizing classes. $(".modalform").submit(function(event) { /* prevent form from submitting normally */ event.preventDefa ...

Adapting the column width to display or hide content with CSS styling

I have a row with 2 columns. The left column contains my main content and the right column is a chatroom. I would like users to be able to minimize and open the chatroom, which I already know how to do. However, when the chatroom is open, I want the left ...

Encountering a 404 error while trying to delete using jQuery

I have been attempting to execute a 'DELETE' call on an API, but so far I have had no success. Despite being able to access the URI and view the JSON data, my DELETE request does not work. Interestingly, other web services are able to perform thi ...

Using three.js to set the HTML background color as clearColor

How can I set the HTML background as clearColor using three.js? Here is the code snippet for three.js: // Setting up the environment var vWebGL = new WEBGL(); var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera(75, window.innerWidth / ...

Can you explain the purpose of the equals sign in ngRepeat?

Can you explain the significance of the equals sign in the ng-repeat attribute value? <li ng-repeat="person in people = (people | orderBy: firstname)"> rather than using: <li ng-repeat="person in people | orderBy: firstname"> I coul ...

Encountering a 404 error while accessing my meticulously crafted express server

After ensuring that the server is correctly set up and without any errors related to imports or missing libraries, I utilized cors for development purposes. A 404 error persisted even after attempting to comment out the bodyparser. https://i.stack.imgur.c ...

The element is implicitly assigned an 'any' type due to the fact that an expression of type 'any' cannot be used to index types in nodejs and solidity

I am in need of setting networks in my contract using NodeJS and TypeScript. Below is the code I have written: let networkId: any = await global.web3.eth.net.getId(); let tetherData = await Tether.networks[networkId]; Unfortunately, I encountered ...

What is the preferred default value for a property awaiting assignment from a GET response: Undefined or Null?

Say I need to display information about a product, but first I must make a GET request to get the data and assign it to the product. I'm wondering, should the default value for product in the data() function be undefined or null, and is there a differ ...

"Exploring the intricacies of routing within a Node.js application

I previously had around 100 blogs displayed on the "/" page with links for sorting by date (a-z). When clicking on these links, I am redirected to different routes - one is "/sort_by_date" and the other is "/sort_alphabetically". Unfortunately, I was unabl ...

Issue encountered: The date filter does not seem to be functioning properly when dealing with datetime

When I use the date filter to format my date, it works fine for dates alone. However, when I try to include date and time together, it doesn't work as expected: <tr class='clickable-row' ng-repeat="exam in examlist" ng-click="gotoProfile ...

Mishandling of string interpretation

I'm having trouble converting ANSI color codes from console output into HTML. While I discovered a script that can handle this task, I am struggling to make it parse the strings within node js properly. Even when I attempted to JSON.stringify it to in ...