Leveraging information obtained from a single asynchronous API request for another

I am facing a challenge with handling asynchronous data calls in AngularJS.

The scenario is that I will receive multiple objects in an array from one API call, and then I need to enhance those objects with additional data from another API call.

My initial thought was to use nested async calls, but I'm struggling with how to properly implement this using the $q service. I have a service set up to return the extended objects from the second call, which I plan to use in a controller for displaying content in a view.

The first API call provides parameters required for the second API call to retrieve relevant data, which will then be returned to the controller.

To achieve this, I understand that I need to iterate through the results of the first call and make subsequent API requests within that loop. However, my main concern is how to handle returning this data back to the controller. Resolving the promise after the first loop iteration is not feasible due to the nature of asynchronous operations.

What would be the ideal solution for tackling this issue?

Edit: Here is my challenge translated into pseudo-JavaScript:

returnListOfStuff().then(function (data) {
    var result = data.Result;

    for (var i = 0; i < result.length; i++) {
        var dataForListItem = null;

        returnDataForListItem(result[i].ID).then(function (data) {
            dataForListItem = data;
        });

        for (prop in dataForListItem[0]) {
            result[i].prop = dataForListItem[0][prop];
        }
    }

    return result;
});

It's evident that this approach won't work as expected since it only fetches results from the initial call returnListOfStuff(). The issue lies in the fact that the actions inside the for loop are not yet resolved. I'm unsure how to leverage $q.all() in this context, as I lack the necessary parameters from the returnListOfStuff function at that stage.

Answer №1

I'm struggling to use $q.all() in this scenario since the parameters from the returnListOfStuff function are not available yet.

You can handle this in the then callback where you have access to them.

To obtain a promise for the modified result, you can return the promise generated by $q.all from within the callback.

returnListOfStuff().then(function (data) {
    var result = data.Result;
    return $q.all(result.map(function(resultItem) {
        return returnDataForListItem(resultItem.ID).then(function (data) {
            for (prop in data[0]) {
                resultItem[prop] = data[0][prop];
            }
            return resultItem;
        });
    }));
});

Answer №2

Consider utilizing $q.all() in this scenario:

var queue = [];
var itemData = null;
for (var x = 0; x < outcome.length; x++) {
    queue.push(returnItemData(outcome[x].ID));
}

$q.all(queue).then(function(data){
    itemData = data;//or data[0], I'm not sure about Your data structure;
});

If you encounter issues with the value of x, consider using:

for (var x = 0; x < outcome.length; x++) {
    (function(y) {
        queue.push(returnItemData(outcome[y].ID));
    })(x);
}

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

Encountering an issue with resolving the module - Material-UI

I am encountering an issue when trying to import a component from 'Material-Ui'. I am currently working with React and Webpack. My goal is to utilize the "Card" component (http://www.material-ui.com/#/components/card). The import statement for C ...

Ensuring the absence of values in deconstructed variables within an object

In my quest to efficiently destructure the end_time property from the this.props.auction object, I encountered the code snippet below. const {auction: {auction: {end_time}}} = this.props; The problem with this code is that the constant will be undefined ...

Attempting to format a number using a computed property and .toLocaleString() fails to execute

I am facing an issue with the formatting of a number displayed in a <p></p> element. The number is coming from a range input element that is bound to an amount data property using v-model. Even though I have a computed property to format the nu ...

Activate the Air-mode feature in Summernote in addition to the standard toolbar

Is it possible to have both the default toolbar and air-mode toolbar enabled in the Summernote editor? For instance, I would like the user to utilize the default toolbar for general text editing, but have the air-mode toolbar appear when they select a spe ...

Puzzle: Ensuring all properties of JavaScript objects within an array are defined

Consider the vue.js object provided below: FormattedData: Object 1: Object approved: true 2: Object approved: undefined 3: Object approved: false 4: Object approved: true Seeking a more effective and concis ...

React Router 6 and MirageJS redirect error - struggling to understand why this error is occurring

I am in the process of developing the Vanlife app for my React Router 6 course on Scrimba and I have encountered an interesting issue (similar to this user here https://www.reddit.com/r/react/comments/13hdttx/help_me_with_react_router/?sort=new). In our p ...

I can't seem to figure out what's causing this error to pop up in my coding setup (Tailwind + Next.js). It

I've been struggling with this problem for a week now and despite my efforts, I haven't been able to find a solution yet. However, I have made some progress in narrowing down the issue. The problem arises when I try to execute the yarn build comm ...

Divide the table row and store each cell using regular expressions

Here is the original source text: gi0/1 1G-Fiber -- -- -- -- Down -- -- Access gi0/2 1G-Fiber -- -- -- -- Down -- -- gi0/3 1G-Fiber -- -- -- -- Down -- -- gi0/4 1G-Fiber -- -- -- -- Down -- -- gi0/5 1G-Fiber -- -- -- -- Down -- -- gi0/0/1 1G-Fiber -- ...

Issue with accessing $index.$parent in function parameter within ng-repeat in AngularJS

Can anyone with more experience please explain to me why this particular code compiles successfully: <li class="btn dropdown top-stack breadcrumb-btn" ng-repeat="nodeName in selectedNodeNames"> <a class="dropdown-toggle btn-anchor"> ...

Is it possible to retrieve data from an array by using a string variable as the identifier?

How can I retrieve data for a specific argument (a string) from my JSON array by using the argument as the property name? let data = file.[argument]; console.log(data) The value of argument is the property name that I am extracting. The variable file has ...

Show the entire image at its original size within an HTML5 Canvas of specific dimensions by utilizing JavaScript and potentially CSS styling

Is there a way to display an image within an HTML5 Canvas of a specific height and width while maintaining the image's aspect ratio? I need the image to appear at 100% size within a scrollable container. The image I want to use is of a tree: '&a ...

Retrieving the value of the selected radio button

How do I access the value of a clicked radio button? I am trying to create a custom filter based on the gender selected in my <form>. However, when using the filter and orderBy in my ng-repeat, it is not functioning correctly. You can view an examp ...

Does jQuery's implicit loop make bidirectional movement?

It turns out that jQuery's concept of "implicit looping" works in both directions: <div class="classOne"> some content </div> <div class="classOne"> some content 2 </div> [...] $(function() ...

Validate that a string is a correct file name and path in Angular without using regular expressions

Currently, I am using regex to determine if a string is a valid file name and path. However, when the string length becomes longer, it ends up consuming a significant amount of CPU, resulting in browser performance issues. public static readonly INVALID_F ...

The style of MUI Cards is not displaying properly

I've imported the Card component from MUI, but it seems to lack any styling. import * as React from "react"; import Box from "@mui/material/Box"; import Card from "@mui/material/Card"; import CardActions from "@mui/m ...

Error encountered while using Google Translate with XMLHttpRequest (Missing 'Access-Control-Allow-Origin' header)

Trying to access a page that utilizes Google Translate is resulting in the following error: XMLHttpRequest cannot load http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit. No 'Access-Control-Allow-Origin' heade ...

Tips for dynamically adjusting PHP images based on screen size

I am facing issues with page speed due to the images I receive from the server. I am wondering if it's possible to request different image files based on the screen size that the page is being displayed on. I came across this code snippet: if( typeof ...

Unable to show outcomes utilizing angular-ui autocomplete

While attempting to incorporate something similar to the Google Map example from the angular-ui bootstrap demo page, I encountered an issue where the results were not displaying in the dropdown menu. If you'd like to view the full code, you can visit ...

Modify JSON date format to a shorter version using the first 2 letters of the month and the year

Looking to convert date values in a JSON array from "December 2016" format to "D16". Hoping to accomplish this using Regex, any assistance would be greatly appreciated. [["November 2016","December 2016","January 2017","February 2017","March 2017"],["tot ...

What is the most efficient way to update a row in an HTML table using Jquery with the contents fetched from a specific URL?

In this particular snippet of code, I have encapsulated each row in a table within a div that needs to be refreshed periodically. The idea is to call a URL with the div's ID as a parameter and receive updated HTML content for each row from the server. ...