Tips for handling HTTP responses prior to initializing a data-table in AngularJS

Here is a snippet of code showcasing a process involving multiple http requests and the use of promises:

The first step involves calling a service to initiate an http request. Upon receiving the response, a map is created based on the data, which will be used later in the process. Subsequently, a new http request is made within a data-table function, where operations are performed using the previously created map before displaying the data.

However, a challenge arises as there is a delay in obtaining the response from the initial $http call. The attempt to incorporate promises to ensure that the map is created before executing the second http call has not been successful. Any guidance on how to effectively use promises in this scenario would be greatly appreciated.

//Initiating a call to the service for the first http request
    MasterServices.getAllCustomers().then(function(result) {
            $scope.resultdata = result.data;
            $scope.resultdata.forEach(element => {
                //Creating a map holding id and name information
                $scope.oumap.set(element.companyId, element.companyName)
            });
        });
    
    //Configuring the Data-Table
    vm.dtOptions = DTOptionsBuilder.fromFnPromise(function() {
        var defer = $q.defer();
        
        //Executing an http call to retrieve configuration data
        MasterServices.getCompConfig().then(function(result) {
            
            angular.forEach(result.data, function(val) {
                if ($scope.oumap.has(val.compId)) {
                    val.companyName = $scope.oumap.get(val.compId);
                } else {
                    val.companyName = " ";
                }
            });
            defer.resolve(result.data); 
        });
        return defer.promise;
    }).withPaginationType('full_numbers').withOption('createdRow', createdRow);

Answer №1

To simplify your code, consider utilizing async-await in accordance with the ECMAScript version you are targeting.

// Ensure to handle potential errors with a try-catch block for failed HTTP requests
const result = await MasterServices.getAllCustomers();
$scope.resultdata = result.data;
$scope.resultdata.forEach(element => {
    // Create a map containing id and name pairs
    $scope.oumap.set(element.companyId, element.companyName)
});

// Once the HTTP response is received, proceed with other operations.

If for any reason you cannot implement the above approach, ensure that your "Setting Data-Table" section of code is placed within the success callback of the initial promise.

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

Can a SVG Animation be created featuring a progress ring with both the right and left dash offsets moving simultaneously?

Currently in my codepen, I am working on a project where I am using GSAP. If you are unfamiliar with that, no worries - just focus on the dashoffset and dasharray in the SVG circulation path. You can find this project in Codepen which is part of our premi ...

The disappearance of the checkbox is not occurring when the text three is moved before the input tag

When I move text three before the input tag, the checkbox does not disappear when clicked for the third time. However, if I keep text three after the input tag, it works fine. Do you have any suggestions on how to fix this issue? I have included my code be ...

Guide on altering the Class with jquery

Here is My jQuery Code: $('a#cusine1').on('click', function(){ $('div#product-list').html("LOADING..........").show(); $(".ccid").addClass("0"); document.getElementById("ccid1").className="acti ...

The PUT Method encounters errors when the model string contains a value that interacts with the web API

Here is a webapi method that I am working with: // PUT api/Competitions/5 public HttpResponseMessage PutCompetitor(int id, CompetitionViewModel competitorviewmodel) { ... } The structure of the CompetitionViewModel is as follows: public class Compe ...

Exploring Cross-Domain Scripting with Rest-Angular and Rails

I'm currently developing an application using Rest-Angular and Rails. Angular is operating on localhost:9000 while Rails is on port 3000. Unfortunately, I've encountered some cross-domain issues that are preventing me from sending POST requests. ...

Effortlessly apply mapping, filtering, reducing, and more in JavaScript

Array#map and Array#filter both create a new array, effectively iterating over the original array each time. In languages like rust, python, java, c#, etc., such expression chains only iterate once, making them more efficient in certain cases. While this ...

An error occurred while trying to serialize the `.res` response received from the `getServerSideProps` function in

I encountered the following issue while utilizing the getServerSideProps function to fetch data from Binance API. import binance from "../config/binance-config"; export async function getServerSideProps() { const res = await binance.balance(( ...

FirebaseError: The type 'Hc' was expected, but instead, a custom Yc object was provided

I've encountered an issue while attempting to perform a batch entry. The error I'm facing involves passing an array in a .doc file. Interestingly, this approach seems to work perfectly fine on another function where I pass an array into a .doc us ...

A guide on utilizing URL parameters in Express.js to deliver images as static files

Looking to dynamically serve images from an "images" directory in my project based on user input, how can I achieve this? For instance, https://localhost:3000/images?fileName=burger This URL should display the corresponding image in the browser. If any ...

Looking for a way to assign customized thumbnails to images in react-responsive-carousel and react-image-magnifiers?

I am currently working on a product viewer using react-responsive-carousel and react-image-magnifiers. Following an example from this GitHub repository, I encountered an issue with mapping custom thumbnails correctly. Although hard-coding the array works f ...

What is the standard root directory in the "require" function's context?

After spending hours struggling to set up a simple "require" command, I've come to the conclusion that var example = require("example") only works if there's an example.js file in the node_modules directory of the project. I'm encountering ...

Enhancing Connectivity Through Fastify and Fastify-HTTP-Proxy Integration

I'm currently utilizing fastify along with fastify-http-proxy on a VPS running Ubuntu 19.x that is equipped with three unique IPv4 addresses. I have confirmed the functionality of these IP addresses by testing them using the following example IPs: cur ...

Vue alert]: The element "options" is not declared in the current instance but is being referenced during the rendering process. Facing problem with Vue JS

Encountering an error while rendering the project. I've thoroughly checked all details but couldn't pinpoint which line is causing the issue. The console displays the following warning: Vue warn]: Property or method "options" is not defined on th ...

Reveal or Conceal Information Depending on Cookie Status

Below is the Jquery code I am using: $("#tool").click(function() { $(".chelp").slideToggle(); $("wrapper").animate({ opacity: 1.0 },200).slideToggle(200, function() { $("#tool img").toggle(); }); }); When the #tool img is clicked, bot ...

Tips for efficiently importing a file or folder that is valuable but not currently in use

I'm struggling to find any information about this particular case online. Perhaps someone here might have some insight. I keep getting a warning message saying 'FournisseursDb' is defined but never used no-unused-vars when I try to import t ...

Setting the 'redirect_uri' for Identity Server 4 in a React JS application and directing it to a specific view using a route

After following the instructions at , I attempted to login to Identity Server from my ReactJS application. Upon successful login, http://localhost:3000/callback.html was loaded with id_token and access_token in the URL. However, I noticed that this callbac ...

Steps for Integrating a Web Service Reference in NodeJS

Can a Web reference be added to a NodeJS project similar to how it's done in .NET framework Web API Projects? Essentially, the NodeJS API project will serve as a middleware between the Front End and an XML Web service. The XML Web service is a secure ...

Changing the application's state from within a child component using React and Flux

UPDATE It seems that my initial approach was completely off base. According to the accepted answer, a good starting point is the TodoMVC app built with React + Flux and available on GitHub. I am currently working on a small React + Flux application for ed ...

Resize the main container to fit the floated elements

I've been working on constructing a family tree, and the last part of the functionality is proving to be quite challenging for me. My family tree consists of list elements that are all floated to the left. Currently, when the tree expands beyond the ...

Will synchronous programming on an Express server prevent other users from accessing the page simultaneously?

Currently working on a simple one-page web app that depends on loading weather data from a file. To avoid multiple HTTP requests for each visitor, I have a separate script refreshing the data periodically. In this particular instance, I am using fs.readFi ...