"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

Vanishing Span in CSS3 Flexboxes

I came across this particular HTML code: <div class="panel panel-info"> <div class="panel-heading">Person</div> <div class="panel-body"> <div class="data"> <p class="keys"> ...

Tips for invoking a function from a JavaScript file within an Angular component

This particular query remains unanswered and pertains to AngularJS. I am seeking a solution specifically for Angular, as none of the existing answers online seem to be effective in my case. Here is an outline of my code: Columns.js export class Columns { ...

Changing the text during a reset process

I've been grappling with this issue, but it seems to slip through my fingers every time. I can't quite put my finger on what's missing. My project involves clicking an image to trigger a translate effect and display a text description. The ...

Updating the content of a div when the mouse hovers over it

Looking for some help here - I have a few divs with paragraphs of text inside. My goal is to change the text in each div when it's being hovered over. I know this can be done using JavaScript (jquery perhaps?), but my coding skills are pretty basic. A ...

The URL in a request is altered prior to execution

I am encountering an issue with my NodeJS application where it automatically appends my domain to the URL set in my http request. How can I prevent this from happening? I have tried to search for similar problems but have not found any relevant solutions. ...

Retrieving information from a virtual document in a 'pre' save hook using Mongoose

Seeking help with utilizing data from a recently created document to update a value using a 'pre' hook. An example of the model being used: ... title: { type: String, required: true }, company: { type: mongoose.Schema.ObjectId, ref: &ap ...

Setting up Nginx, Node, and Angular to work together with a subfolder in the API/

Currently, my node/angular application runs smoothly when directed to the configured port (8081 for explanation purposes). I am able to perform post, get, put, and delete operations as expected. My objective is to have the node application running on mydo ...

Is it possible to manually trigger a version change transaction in IndexedDB?

I have been working on a Chrome extension that uses the IndexedDB to store data client-side in an IDBObjectStore within an IDBDatabase. The data structure requires users to be able to modify the object store freely, such as adding new objects or modifying ...

Incorporating JavaScript and CSS files into a content page of a master page in ASP.NET: Steps to follow

I am facing an issue with adding javascript files and css to a content page of a master page in asp.net. I attempted to include a datetime picker on my ContentPage, but it only works on the masterpage. When I try to add the same code to my contentpage, i ...

Integrate, Delay, Experimentalize, and Attach components

This inquiry might lean more towards a general browser/javascript discussion rather than a focused prototype question, but I believe this community possesses a deep understanding of javascript and browsers. With that said, here is my query: If the followi ...

Unable to load more than one controller in a single partial view using AngularJS

I am having trouble loading a second controller to populate a select in my view. Despite my efforts, it just won't cooperate. This is the code snippet I'm using: app.js (function() { 'use strict'; angular .module('app.lazylo ...

Converting a string to JSON format with JavaScript

My string is structured in JSON format like this: "{""c1"": ""value1"", ""c2"": ""value2""}" After storing it in an SQLITE database, I use the following Javascript code to retrieve it back as JSON: var req= "SELECT json_column from my_table"; var re ...

Upgrade angular-chart.js when applied to a filtered collection

I recently started working with Angular and encountered an issue while incorporating Angular Charts JS. I have a list that can be filtered using search text, and I want my charts to update whenever the list is filtered. What would be the best approach to ...

I am having trouble with the sorting functionality of the Orderby filter in the angular.filter plugin. It does not

I am utilizing the Angular Filter plugin to group the tr's in a table based on the "Row" parameter. The code below constructs the Tr according to the Row value <tbody> <tr ng-repeat="row in data |groupBy: 'Row' | orderBy : & ...

The art of sketching precise lines encircling a circular shape through the

What is the best way to use a for loop in JavaScript to draw lines around a circle, similar to those on a clock face? ...

Oops! There seems to be an issue with an invalid character in the literal true value while making a POST request to the API with JSON data. The expected character should be

Can anyone help me solve an issue I am facing while trying to use the POST method to insert data using JSON in JS code? When I attempt the transformation, I receive an error message stating: "ERROR: invalid character ' ' in literal true (e ...

A declaration of "import '***.css';" was located within an ECMAScript module file in the monaco-editor npm library

It's perplexing to me why the developers of monaco-editor included these statements, as they are actually causing errors in my browser such as: Failed to load module script: Expected a JavaScript module script but the server responded with a MIME typ ...

Attempting to iterate over elements within an object labeled as strIngredients 1-15

event.preventDefault(); $('#mainContent').empty(); $.ajax({ url: randomDrinksURL, method: 'GET' }).then(function (response) { console.log(response); var mainContent = $('#mainContent&ap ...

What is the best method for displaying an HTML string within an HTML file in Angular 5?

I have declared an array in my TypeScript file like this: import {Component, OnInit} from '@angular/core'; import { DomSanitizer } from '@angular/platform-browser'; @Component({ selector: 'app-foo', template: ...

I'm curious about the origin of this.on event handler. Is it part of a particular library or framework?

While casually perusing through the application.js file in the express source code, I stumbled upon this interesting piece of code. I'm curious about the origin of this '.on' event. Is it part of vanilla JavaScript or is it a feature provid ...