Optimizing AngularJS promises for better performance

I have spent a considerable amount of time researching this topic, however, the tutorials and guides I've come across have varied significantly, making it difficult for me to fully understand this concept.

What I aim to accomplish is as follows:

1) Initiate a straightforward http request from our server [Using any API for illustration purposes]

2) Execute a function with data retrieved in step (1). [Removing a property from the object]

3) Utilize the result and length from step (2) to carry out a loop of $http requests to our server. [Or any server]

4) This will yield 6 distinct objects. Apply a function to these 6 objects. [Adding a property]

5) Only after completing all the aforementioned steps, execute a separate function [Logging "finished"]

How can promises be used to achieve this? How do I pass data from step (1) through a promise to step (2)? Is this the correct approach to accomplish my task?

If someone could demonstrate how this structure should be organized, it would be extremely beneficial; I have kept the functions simple for the sake of clarity in this inquiry.

Answer №1

Indeed, utilizing promises is a great way to organize solutions for these types of issues.

Below is a simplified solution, presented in pseudo-code form:

$http(...)
    .then(function(response) {
        // handle response data, such as:
        var list = reponse.data.list;
        // return the data for use in the next 'then'.
        return list;
    })
    .then(function(list) {
        var promises = [];
        angular.forEach(list, function(item) {
            // make a request for each item
            var promise = $http(...).then(function(itemResponse) {
                itemResponse.extraProperty = true;
                return itemResponse;
            });
            // create an array of promises
            promises.push(promise);
        });
        // merge all promises and return for the next then()
        return $q.all(promises);
    })
    .then(function(itemsList) {
        // itemsList now contains an array of processed item responses.
        console.log(itemsList);
    });

(Please note that this code has not been tested.)

The example demonstrates how you can pass values in callbacks to be used in the subsequent then() or pass a promise to trigger the next callback upon resolution. Using $q.all() combines multiple promises into one, resolving only when all have resolved.

Edit: It is possible to omit these three lines:

        return list;
    })
    .then(function(list) {

However, including them enhances readability by clearly separating tasks.

Answer №2

Review the code snippet below for potential syntax errors, but focus on the overall structure. In Step3, there are six $http requests that need to be completed before a unique response object (an array) is returned, each containing the response for every $http request.

//Step 1
var Step1 = function () {
    $http.get('api/controller').success(function (resp) {
        var object1 = resp;
        Step2(object1);
        Step3(object1).then(function (resp) {
            //resp.data is an array with responses from each $http request
            Step4(resp);
            Step5();
        });
    });
}

//Step2
var Step2 = function(obj){
    //perform actions on the object
}
//Step3
var Step3 = function (object1) {
            var call = $q.defer();
            var get1 = $http.get(object1[0].url);
            var get2 = $http.get(object[1].url2);
            //...
            var get6 = $http.get(object[5].url6);

            $q.all([get1, get2,..get6]).then(function (resp) {
                call.resolve(resp);
            });
            return call.promise;
        }
//Step4
var Step4 = function (resp) {
    for (var i=0; i<resp.data.lenght;i++){
        PerformAction(resp.data[i]);
    };
}
//Step5
var Step5 = function () {
    alert("Process Complete");

}

Step1(); //Invoke Step1 function

Answer №3

Having trouble with the implementation? Consider incorporating $q.all():

var config1={method:'GET',url:'/api/...'};

$http(config1).success(function(resultsFrom1){
  functionForResultsOf1(resultsFrom1);
})


var functionForResultsOf1 = function(resultsOf1){
//modify results synchronously
resultsOf1.splice()...;
var promises=makePromises(*pass whatever you want*);
 $q.all(promises).then(function(aggregateOfAllCallsToServer){
    angular.forEach(aggregateOfAllCallsToServer,function(data){
     //manipulate data from server calls

    })

    console.log("finished");

 })
}

 var makePromises = function(serverUrls){

          var promises = [];
          angular.forEach(serverUrls, function(url) {

          var promise=$http({
                url   : '/api/'+url,
                method: 'GET',
          })

          promises.push(promise);
    });

    return $q.all(promises);
 }

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

What is the procedure for initiating a POST request when the payload is ready for submission?

After a successful payment, my success page is displayed with a URL that includes a query parameter. I want to make a POST request to my API endpoint when the page loads, but I'm encountering an issue where the first POST request is empty (router.quer ...

ReactJS - Automatically populate text input with object data upon selection

In my main component App.js, I have a StudentItem object that is rendered. Additionally, there is another component called EditStudentDetails which is initially hidden but should be displayed upon clicking on the StudentItem object. Although I have succe ...

I am encountering an error with addToCart, as I am unable to read properties of undefined when trying to use the 'push' function

import { createSlice } from '@reduxjs/toolkit'; const cartReducer = createSlice({ name: 'cart', initialState: { items: [], }, reducers: { addToCart: (state, action) => { state.items.push(action.payl ...

Creating a hierarchical structure for three interconnected lists within SharePoint Online by utilizing JavaScript

We currently have a network of interconnected SharePoint lists: Department list Category List - which includes a lookup field linked to the Department list. Asset list - with a lookup field connected to the Category list. Is there a method, utilizi ...

Avoiding the need to use brackets inside driver.execute_script

I am facing the issue where Webdriver is unable to locate an element, so I want to create a general solution for this: def check_element(driver, xpath): checked = driver.execute_script( """function getElementByXpath(path) {{return docume ...

The Angular index value cannot be found

While working on my app, I encountered an issue where the index returned as undefined after a successful delete operation. This prevented the item from being removed from the list. Code HTML <div *ngIf="groups.length>0"> <ion-item-slidin ...

What is the reason for the camera being positioned opposite to the typical orientation of the object

Why does the camera at position(0, 0, -1) and lookAt(0, 0, 1) quaternion display as (_x: -3.141592653589793, _y: 0, _z: -3.141592653589793)? This output seems to be contrary to the typical object behavior. I attempted to create a group with the same posit ...

Automatically refresh a pair of pages in sequence

Seeking advice on how to execute the following steps in JavaScript: - Pause for 120 seconds - Access http://192.168.1.1/internet-disconnect (in an iframe or similar) - Pause for 3 seconds - Access http://192.168.1.1/internet-connect - Repeat Here is ...

Is there a way to assess Python code within a document's context using JavaScript in JupyterLab?

When using Jupyter Notebooks, I can create a cell with the following JavaScript code: %%javascript IPython.notebook.kernel.execute('x = 42') After executing this code, in another cell containing Python code, the variable x will be bound to 42 a ...

The sequence in which arguments are executed in the console.log() function

After running tests on both CodeAcademy's editor and Chrome's console, I came across an interesting observation. I noticed that the argument of console.log() is not evaluated first even if it is an expression. Why does this happen? var x = 0; co ...

Struggling to get my JavaScript function for calculating one rep max to work, need some help figuring out the issue

I have been working on a one rep max calculator using the Epley Formula. However, when I try to call the function, it returns as undefined. I have utilized the parameters weight and reps, both of which are parsed as integers, believing that they would be e ...

Client-side sorting in jqGrid

I'm working with a tree-grid that has autoloading rows. My objective is to sort the grid by the tree column directly on the client side. However, every time I click on the column header to sort, it triggers an unnecessary Ajax call for sorting, when ...

Leverage Vue's ability to inject content from one component to another is a

I am currently customizing my admin dashboard (Core-UI) to suit my specific needs. Within this customization, I have an "aside" component where I aim to load MonitorAside.vue whenever the page switches to the Monitor section (done using vue-router). Here ...

Is the AngularJS application failing to transmit data accurately to Node.js?

I've been grappling with this issue for a few days now and I can't seem to pinpoint the problem. As someone relatively new to the MEAN stack, I might be overlooking something obvious. I followed the boilerplate code from mean.io for both the back ...

Scroll through like Uber Eats with horizontal ScrollSpy and navigation arrows

I am in need of a menu style similar to Uber Eats, with an auto horizontal scroll feature for categories that exceed the available width. Additionally, I would like the active links in the menu to change as the user scrolls down, reflecting the current cat ...

Modifying the DOM within a getJSON callback

My current challenge involves fetching data from the YouTube API and displaying it on my website. However, I am facing an issue where the DOM changes made inside the getJSON's callback function are not reflecting on the webpage. Even though I can see ...

Interactive dropdown menu with customizable options and fields

I'm encountering an issue with my combobox and dynamic fields. When I input data into a mysql table from a form that contains dynamic rows, each row includes two comboboxes where the second one depends on the first. Everything works fine on the first ...

How to use jQuery to add a list item to a for loop list in Jinja

I'm encountering a minor issue while attempting to add a list item to a for loop after making an Ajax call. The list item is being appended to the top of the list instead of the bottom where I want it to be placed. Thank you for your assistance. Belo ...

Tips for fixing prettier errors in express and TypeScript code

I have set up a simple Node/Express + Typescript application app.listen(PORT, (): void => { console.log(`app is running in ${environment} and listening on port ${PORT}!`); }); I am encountering an error and I am unsure of the cause? Replace PORT, wit ...

Angular ui router - Transitioning from one state to the same state, when no parameters are provided, results in

Check out the Plunker Demo <script> var myapp = angular.module('myapp', ["ui.router"]) myapp.config(function($stateProvider, $urlRouterProvider) { // If there is no matching URL, go to /dashboard $urlRouterProvider. ...