Combining multiple promises in Angular into a single promise

I have a dilemma with my services - they both return the same type of objects but with different properties based on a flag. These services utilize functions that return promises.

Service 1 - fetchLocations:

this.fetchLocations = function () {
            return $http.get('http://somewhere.com').then(function (response) {
                    return response;
     }).catch(exception.catcher('Something went wrong'));
};

Service 2 - retrieveSpots:

this.retrieveSpots = function () {
            return $http.get('http://somewhere.com/').then(function (response) {
                    return response;
     }).catch(exception.catcher('Something went wrong'));
};

Now, I have a master Service that orchestrates these two services. The challenge is to ensure that the wrapper function doesn't return the combined results until all promises are fulfilled and have returned valid information (or null). My current implementation looks like this:

    this.getCombinedResults = function () {
        var combined= [];

        var apiCalls = [service1.fetchLocations(), service2.retrieveSpots()];

        $q.all(apiCalls.map(function(call) {
            return call;
        })).then(function (response) {
            angular.forEach(response, function (item, index) {
                combined.push(item);
            });
        });            
        return combined;
    };

I suspect there might be an issue with how I'm handling multiple promises in the wrapper service. When I invoke the wrapper function, it returns null. I need to investigate this further, but any insights on whether my approach is correct would be greatly appreciated. Thank you.

Answer №1

To ensure that the getCombinedResults function successfully combines results from a promise-based service, it is crucial for this service to also return a promise. Otherwise, the merged data will always be empty.

The following code snippet demonstrates how to achieve this:

 return $q.all(apiCalls.map(function(call) {
            return call;
        })).then(function (response) {
            angular.forEach(response, function (item, index) {
                combined.push(item);
            });
            return combined;
        }); 

By using the then method, which itself returns a promise, this code ensures that a promise is returned to the calling function.

The resolved value will be the array combined.

Additionally, when invoking this code, make sure to handle the response using promise-based resolution with then.

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

Looking for a way to transform form values into objects once they have been added to FormData?

Facing an issue with submitting a form using formgroup. Initially, the form value was an object, but after appending it to formdata, the value turns into a string, making it difficult to parse the data in the query. After submitting, the form value of us ...

Mastering jQuery ajax in Google Chrome Extensions

I have developed a script to fetch data from an external server using JSONP request in jQuery. Please take a look at the code snippet below: $("#submit").click(function() { var state = $("#state").val(); var city = $("#city").val(); $.ajax({ ...

Adjust the dimensions of a Three.js generated 3D cube dynamically during execution

Is it possible to dynamically change the dimensions (width/height/length) of a 3D Cube created with Three.js? For example, I found a Fiddle on Stack Overflow that changes the color of a Cube at runtime: http://jsfiddle.net/mpXrv/1/ Similarly, can we modi ...

Fastify route handler failing to start after onRequest hook is executed

I am currently working on a fastify application that needs to capture the raw body of post requests for authentication purposes. After extensive research, I discovered that fastify does not have native support for this feature. The solutions I found online ...

altering the URL of an AngularJS application prior to its initial load

I have encountered an issue with the Instagram API where the result redirects to my app but Instagram does not accept URLs that include the "#" symbol. For example, http://localhost:3000/#/functionalists is not being accepted due to the "/#/". My app use ...

Establishing the httppostedfilebase variable when validation is unsuccessful in an ASP.Net MVC view

I'm currently facing an issue with handling validation errors in my application. I have implemented uploading and downloading images successfully, but when there are validation errors and the controller redirects back to the page, the HttpPostedFileBa ...

What folder layout is best suited for organizing Protractor end-to-end test cases?

Is it best practice to maintain the folder structure for e2e test cases in Protractor identical to that of the application? ...

Waiting for the completion of the ScrollIntoView operation using Selenium

Whenever I try to scroll to a specific element and take a screenshot of the page, the driver captures the screenshot before the page has fully scrolled to the element. To address this, I initially included a time sleep in my code: driver.execute_script(&qu ...

Implementing ReactJs content from one page to another using jQuery ajax

I have been developing an application and have created some views in React Js. I am now looking to load these views onto another page using jquery load. Is this possible? [Let's say leave.html contains the react code. Now, I want to load leave.html i ...

"Render Failure" JavaScript and CSS files

I'm encountering a peculiar issue while attempting to load certain JS and CSS files. Within my ASP.NET MVC Web Project, I have an Index.html file where I've specified the loading of script files. It's worth noting that I have modified the U ...

Buttons for displaying and concealing content are unresponsive

After spending over 6 hours trying to fix this code and searching online, I am completely frustrated. My goal is to hide the login table and its associated background image (#lg #ck) and instead, place a button on top of where the login table is. When thi ...

Issue with THREE.js Line Object not displaying in web browser

Having just recently started to dabble in THREE.js, I encountered an issue where the code only displays a black screen instead of the intended triangle shape. Can someone assist me in troubleshooting the problem within the code? <!DOCTYPE html> &l ...

Getting the updated state value instantly within the useEffect hook

I've been facing an issue where I update the value of a state and then attempt to use it inside useEffect, but I am unable to access the updated state. Can anyone provide guidance on how to retrieve the updated state immediately within useEffect? Tha ...

Using the ng-change directive in an ng-repeat loop within AngularJS allows

Is there a way to cancel out the response in the answer field using an ng-change event on the dropdown box? I need a method to dynamically access the answer field. The code is within ng-repeat tags. For more information, please visit this PLUNKER. ...

Inject $scope into ng-click to access its properties and methods efficiently

While I know this question has been asked before, my situation is a bit unique. <div ng-repeat="hello in hello track by $index"> <div ng-click="data($index)"> {{data}} </div> </div> $scope.data = function($index) { $scope.sweet ...

Chrome's Ctrl-Shift-N event binding

I have implemented jQuery.hotkeys to handle keyboard events. Currently, I am attempting to bind the combination of Ctrl+Shift+N $(document).bind('keydown', 'ctrl+shift+n', function(e) { e.preventDefault(); alert('Ctrl+Shi ...

Implementing a searchable drop-down in AngularWould you like to learn how

I'm struggling with adding search functionality to my dynamic dropdown. If anyone could assist me in implementing the search feature, I would greatly appreciate it. I have successfully created a dropdown with search for static data but am facing chall ...

Obtaining the "match" object within a Custom Filter Selector on jQuery version 1.8

Here's a helpful resource on Creating a Custom Filter Selector with jQuery for your reference. A Quick Overview: If you're unfamiliar with jQuery's Custom Filter Selectors, they allow you to extend jQuery’s selector expressions by addi ...

Sending data with an AJAX post request from JavaScript to a Python backend

Attempting to pass a dictionary from JavaScript to a Python script using AJAX POST method. Here's the JavaScript code: function foo(){ context = { 'var1': val1, 'var2': val2 } $.ajax({ ...

Obtain the selected option's value using Angular

Having an issue with my user.model.ts file. I have a list of users that I can edit by clicking on a button that filters the user's data and puts it in a bootstrap modal. I'm using [ngModel] in a select tag to get the country of my user, but when ...