What is the best method for accessing the service response data when I am sending back an array of custom map with a promise as an object?

Sharing my code snippet below:

function createObject(title, array){
 this.title = title; 
 this.array = array;
}

//$scope.objects is an array of objects


function mapPromise(title, promise){
    this.title= title;
    this.promise = promise;
};

var fetchAllPromises = function(){
    var promises = [];
    angular.forEach($scope.objects, function(object) {
        urlPath = <dynamicurl>+object.title;
        var promise = $http({
            url   : urlPath,
            method: 'GET'
        });
        promises.push(new mapPromise(object.title, promise));
    });
    return $q.all(promises);
};

I am facing a challenge when trying to access the JSON response received from the service in the below .then block. Any suggestions on how I can achieve this?

 fetchAllPromises.then(function(data){
                    angular.forEach(data, function(promiseData){
                        var title = promiseData.title;
                        var responseData = promiseMap.<?> --> How do I retrieve the JSON data here?
<I need to assign $scope.objects.array to data returned by the promise based on each object's title attribute>

                    });
                });

Looking for guidance on this matter as I'm still new to working with promises and AngularJS in general.

Answer №1

One way to accomplish this is by following these steps:

var promises;
angular.forEach($scope.myobjects, function(myobject) {
    var promise = $http({
        url   : urlPath,
        method: 'GET'
    });
    promises.push(promise);
});
$q.all(promises).then(function(resolvedPromises) {
  var firstPushedPromise = resolvedPromises[0];
  //var xPushedPromise = resolvedPromises[x];
}

In the above code snippet, resolvedPromises represents an array where the index corresponds to the order in which the promises were pushed. By utilizing their respective indexes, you can access each promise individually.

It's worth noting that looping over $scope.myobjects seems unnecessary if you're not planning on utilizing myobject.

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

Display irregularly spaced time samples from a MySQL database on a Google Line Chart using a PHP query

Currently, I am utilizing a Line Chart from Google to display data fetched from a MySQL database involving various variables at different time intervals. Although the sample time is set at 1 minute, there are occasions where some data points are lost (for ...

Encountering an issue while trying to initiate npm start command for a ReactJS application on an

While attempting to deploy my node and react app on AWS ec2, I encountered an issue. The node app is working fine, but the react app is giving an error when running npm run build. I also tried using npm start, but unfortunately, it resulted in the same er ...

Modifying the 'child' node within a JSON object

Exploring the implementation of d3s Collapsible tree using a custom node hierarchy. My dataset structure deviates from the norm, for example: http://jsfiddle.net/Nszmg/2/ var flare = { "Name": "Example", "members": [ { "BName":"Ja", ...

Looping through an array of JSON objects in Javascript results in finding instances, however, the process records them

Currently, I am executing a script inside a Pug template. The script commences by fetching an array of JSON objects from MongoDB. I then stringify the array (data) and proceed to loop through it in order to access each individual JSON object (doc). Subsequ ...

When attempting to render 2 components based on the results of 2 fetch calls using Promise.allSettled(), I encounter difficulties if one of them throws an error

I have encountered an issue while using Promise.allSettled() in sending two fetch calls. I am rendering components based on the result - a component with data if it is fulfilled and an error component if rejected. However, when one of the fetch calls throw ...

What is the best way to eliminate the bottom border of an input field?

Seeking advice on how to eliminate the border-bottom of an input field when typing starts. .car-list-input { font-family: 'Source Sans Pro', sans-serif; border-radius: 3px; font-size: 14px; font-weight: 400 !important; height: 35px; ...

JavaScript, PHP handlers, and CommentBox all work together seamlessly to create

$("#login").click(function(){ $.getJSON("handlers/Login.php?name="+$("#username").val(), function(data){ console.log(data); //retrieves data from login box and sends it to the handler, returning a JSON array }); template = $("#hid ...

Learn how to effectively utilize templateURL in an express and angular project

Our project utilizes Express without any view engine. To set up static directories, we have the following: app.use(express.static(__dirname + '/public')); app.use(express.static(__dirname + '/view')); app.use(express.static(__dirname + ...

Arrange the grid in a pleasing manner

I'm really struggling with this issue. In my current setup, I have a Grid container that holds two separate grids - one for a textfield and another for a checkbox. Unfortunately, I can't seem to get them to align properly. <Grid container& ...

I'm curious about integrating Font Awesome into my React.js project - any tips on

I'm having trouble getting Font Awesome to display in my React JS project. Here is the code I am using: import React, {Component} from 'react' import './category.css' import axios from 'axios' import Course from './c ...

Steps for rearranging the order of CSS grid layout

Could you assist me in implementing a grid layout that fulfills these specific criteria? I'm unsure of how to proceed, so any guidance would be greatly appreciated. When there are more than 9 items, the current layout changes the order from top to bo ...

The functionality of the JavaScript animated placeholder seems to be malfunctioning

I am currently working on a code that updates the placeholder text every 2 seconds. The idea is to have it type out the letters one by one, and then erase them in the same manner. Unfortunately, the code is not functioning as expected. As a newcomer to J ...

Retrieve data from an array of objects nested within another object

Imagine a scenario where there is an object containing an array of objects. let events = { "id": 241, "name": "Rock Party", "type": "party", "days": [ { "i ...

Tips for showing/hiding textboxes based on select options:

I am currently working on a project that allows users to enter their personal information. I need help figuring out how to show or hide textboxes based on the selection made in a dropdown menu. The dropdown menu in question is for marital status. The opt ...

Can regular expressions be employed to match URLs with $urlRouterProvider in AngularJS?

My goal is to create a regex expression that matches all strings in my routing config which do not start with "/pt/" or "/en/". Additional text may be present in these strings. This is what I have so far: $urlRouterProvider.when('^(?!/(pt|en)/).*&ap ...

Please consider opening in a new tab rather than a new window

<a href='#' onclick="loadpage();">[RANDOM PAGE]</a> Whenever this code is clicked, the following function gets executed. function loadpage(){ $.ajax ({ type: "POST", url: "fetchpage.php", data: "showpage=1", success: function(msg) { ...

Is there a way for me to adjust the typography background based on its current status?

Is there a way to dynamically adjust the background color of text based on the status value? Currently, when the status is pending, the background color defaults to yellow. For example, if the status changes to complete, I want the background color to ch ...

Trying to send headers again after they have already been sent - How to add new users using NodeJS

I'm currently working on an application that involves integrating Google Maps API, NodeJs, Express, MongoDB, Mongoose, and AngularJS. However, I've encountered a challenge that I haven't been able to resolve by looking at similar questions a ...

Turn off the extra space inserted by DataTables

Help needed with centering table header text. <table class="table table-bordered table-hover center-all" id="dataTable"> <thead> <tr> <th scope="col" style="text-align: center">Nam ...

performing functions concurrently within angularjs

I am currently utilizing angularjs 1.0 within my application. There is a dropdown on my cshtml page <select tabindex="2" id="Employee" ng-model="models.SelectedEmployee" ng-change="changeEmployee()" disabled="disabled" class="Answer" size="6"> < ...