Performing multiple http requests in a loop and combining the retrieved data using AngularJS

I am currently working with a piece of source code that looks like this:

var projectPromises = $http.get('http://myapi.com/api/v3/projects?private_token=abcde123456');

  $q.all([projectPromises]).then(function(data) {
    console.log(data);
    return data[0];
  }).then(function(projects) {
    var data = projects.data;
    var promises = [];
    var file = [];
    for(var i = 0; i < data.length; i++){
       var url = 'http://myapi.com/api/v3/projects/' + data[i].id + "/owner";
       promises.push($http.get(url));

    }

    console.log(promises);
    $q.all(promises).then(function(user) {
      console.log(user);
    }, function(error) {
      console.log("error here");
      console.log(error);
    });

Allow me to elaborate on the intention behind my source code.

To begin, the initial API call retrieves a list of projects which I store in projectPromises. After obtaining the project list, each project contains an ID. Subsequently, I iterate over the projects and send corresponding HTTP requests to retrieve the owner of each project.

Following that, I utilize Angular's q module to defer the promises array and display it in the console using:

console.log(user);

In this section, nothing is being logged. Upon further investigation, I discovered that certain projects do not have a user list. In such cases, a 404 error occurs, while a 200 status code is returned otherwise. As a result, the promises array contains objects from both scenarios, causing errors when deferring the promises using Angular q. Unfortunately, I am unsure how to address this issue.

The ultimate goal of this script is to retrieve the owners of each project and store them in an array.

Answer ā„–1

Instead of using $q.all() unnecessarily, you can simply call $http.get().then() as it returns a promise.

After obtaining the list of project IDs, create an array of promises with a .catch() for error handling if any request fails.

Once you have all the promises in the array, utilize $q.all() followed by one more .then() to complete the process.

var pProjects = $http.get('http://myapi.com/api/v3/projects?private_token=abcde123456');

pProjects
    .then(function (result) {
        // map the project IDs to an array of promises for each project's owner
        var pProjectOwners = result.data.map(function (proj) {
            return $http
               .get('http://myapi.com/api/v3/projects/' + proj.id + '/owner')
               .then(function (result) { return result.data; })
               // fallback value for failed requests
               .catch(function () { return 'no owner'; });
        });

        return $q.all(pProjectOwners);
    })
    .then(function (projectOwners) {
        console.log(projectOwners);
    })
    .catch(function (error) {
        console.error("something went wrong", error);
    });

Here is a revised version separating out the function to get a project's owner:

function getProjectOwner(projectId) {
    return $http
       .get('http://myapi.com/api/v3/projects/' + projectId + '/owner')
       .then(function (result) { return result.data; })
}

var pProjects = $http.get('http://myapi.com/api/v3/projects?private_token=abcde123456');

pProjects
    .then(function (result) {
        // map the project IDs to an array of promises for each project's owner
        var pProjectOwners = result.data.map(function (proj) {
            return getProjectOwner(proj.id)
               // fallback value for failed requests
               .catch(function () { return 'no owner'; });
        });

        return $q.all(pProjectOwners);
    })
    .then(function (projectOwners) {
        console.log(projectOwners);
    })
    .catch(function (error) {
        console.error("something went wrong", error);
    });

Answer ā„–2

Your promises are becoming unnecessarily complicated. Instead of binding to the http call directly, you can simply interact with the promise that $http returns.

$http.get("http://myapi.com/api/v3/projects?private_token=abcde123456").then(function (results) {
   // projects will be your array of projects
   var projects = results.data;

   // Use native Array for each to get reference to every object in array
   projects.forEach(function (project) {
     $http.get("http://myapi.com/api/v3/projects/' + project.id + "/owner").then(function (results) {
       var data = results.data;
       console.log(data); // This will log your owner
     });
   })
});

Consider nesting your owner with the returned project json to reduce the number of unnecessary http requests. However, this is ultimately a decision dependent on server side architecture.

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

Analyzing DynamoDB Query

I am on a mission to recursively analyze a DynamoDB request made using the dynamo.getItem method. However, it seems that I am unable to locate a similar method in the DynamoDB SDK for Node.js. You can find more information about DynamoDB SDK at http://do ...

concealing the dropdown in React upon clicking outside of it

I have been delving into learning React by challenging myself with a React problem. The code challenge I'm facing involves trying to close a drop-down when clicking outside of it. Despite my efforts to debug, I haven't had much luck in solving th ...

Express.js Server Side Rendering - GET request for '/json/version/'

I have a running express server that pre-renders my react application. The routes file matches the HomeContainer to the base route / and all other routes match to the page not found. import HomeContainer from 'containers/home-container/home-container ...

Why is it that in IE9, submitting a basic form using jQuery doesn't seem to work?

Take a look at the code snippet below: <html> <head> <style type="text/css"> #myform {display:none;} </style> </head> <body> <button type="button" id="uploadbutton">Upload Images</button> <form name="myf ...

What is the reason behind the necessity of using setTimeout with a delay of at least 50ms for JS .focus()

Problem While creating a page for a client at work, I encountered an issue with a slide-out search bar. When clicking the button to open the search input field (which starts off hidden), I want the focus to shift to that input field. Oddly, I found that ...

What is the process for adding information to datatables using jQuery?

I have been struggling to make a data table in jQuery function correctly. I am able to append data to the table, but the sorting, pagination, and search features are not working. Even though the data is visible in the table, it shows as 0 records. I am wor ...

Next JS Dynamic Routing displays successful message on invalid routes

I have been using the App Router feature in Next JS along with Strapi as my CMS. When I make a query to the API endpoint in Postman, I receive the expected results. Requests for routes without corresponding slugs return a 404 error, while only routes with ...

What is the best method for uploading a JSON file to a React web application and retrieving the file's link?

Is there a way to upload a JSON file to my React application and obtain the link to that file? Our app developer is working on implementing app linking and has requested this functionality. ...

Search the table for checked boxes and textboxes that are not empty

Could you suggest alternative ways to express the following scenario? I have a table with 3 rows. Each row contains a column with 3 checkboxes and another column with just a text box. I would like it so that when the values are retrieved from the database ...

Moving a Ball Back and Forth Using Three.js

Iā€™m looking to create a continuous motion for a Ball in Three.js, where it moves to the right, returns to its starting position, and then repeats the sequence. var geometry = new THREE.SphereGeometry( 5, 32, 32); var material = new THREE.MeshPhongMateri ...

An issue arises with the Datatables destroy function

Utilizing datatables.js to generate a report table on my page with filters. However, when applying any of the filters, the data returned has varying column counts which prompts me to destroy and recreate the table. Unfortunately, an error message pops up ...

What is the optimal approach for managing server-side data stored as a JavaScript variable?

When dealing with global variables like JSON inserted into a web page server side with PHP, the best way to handle it is up for debate. Options might include leaving it for garbage collection, omitting var initialization and deleting the variable, or simpl ...

What is causing the newly generated input tags to disappear from the page?

I'm having an issue where my code successfully creates new input tags based on user input, but they disappear shortly after being generated. What could be causing this to happen? <form> <input type='text' id='input' /> ...

A quick guide on automatically checking checkboxes when the user's input in the "wall_amount" field goes over 3

I'm looking to have my program automatically check all checkboxes (specifically "Side 1, Side 2, Side 3 and Side 4") if the input for wall_amount is greater than 3. Is there a way to achieve this? I attempted lines 10-12 in JavaScript without success. ...

Guide for implementing a one-line if statement in Javascript

I am aiming to assign a class using a single-line if statement as outlined in this source. Currently, I am utilizing Material-UI and attempting to specify a class. Therefore, I would like to implement this approach: if(condition) expression <Typogr ...

A guide on how to successfully send multiple arguments to a single Javascript method by utilizing thymeleaf onclick (th:onclick) functionality

I attempted to use the code below, but unfortunately it did not work as expected. Can you please provide me with a solution? Javascript Code ---> function passValue(id, name){ console.log(id) console.log(name) document.getE ...

Functionality in Three.js that involves selecting nearby objects with an event handler and ensuring that the self object is

I have spent countless hours today diving deep into the documentation, tutorials, and stackoverflow questions in pursuit of a solution to this issue. I am pleading for your assistance ā€“ please take pity on me and help! The problem at hand involves a wat ...

Efficiently generating and managing numerous toggle buttons in Reactjs with Material-ui ToggleButtons

Currently, I am exploring the idea of designing a sidebar that incorporates a variable number of toggle buttons generated from an object containing keys and values. However, I am encountering difficulties in utilizing the "key" value to adjust the corres ...

Having issues with the input event not triggering when the value is modified using jQuery's val() or JavaScript

When a value of an input field is changed programmatically, the expected input and change events do not trigger. Here's an example scenario: var $input = $('#myinput'); $input.on('input', function() { // Perform this action w ...

Utilizing local JSON data with Morris.js: A beginner's guide

I am working on dynamically plotting a Morris line using data from a local file called sales.php (in json format): [ { year: '2008', value: 20 }, { year: '2009', value: 10 }, { year: '2010', value: 5 }, { year: ' ...