AngularJS: Handling multiple asynchronous calls simultaneously in a function

In my AngularJS function, I need to make two asynchronous calls that are independent of each other. However, the function should only return when both calls have completed and the results are stored in the return variable.

I have tried various solutions and ended up using the following approach. Unfortunately, it is quite slow as it waits for the first call to finish before proceeding to the second one.

function myAngularfunction(a, b) {
    var defer = $q.defer();
    var test= {
        a: "",
        b: ""
    };

    msGraph.getClient()
        .then((client) => {
            // First async call
            client 
                .api("https://graph.microsoft.com/v1.0/")
                .get()
                 .then((groupResponse) => {
                    var result = groupResponse;
                    test.a= result.displayName;

                    msGraph.getClient()
                        .then((client) => {
                            // Second async call
                            client
                                .api("https://graph.microsoft.com/v1.0/teams/")
                                .get()
                                .then((groupResponse) => {
                                    var result = groupResponse;
                                    test.b= result.displayName;
                                    defer.resolve(test);
                                });

                        });

                });
        });


    return defer.promise;
}

Function invocation:

myAngularfunction(a, b).then(function(obj)

Is there a way to wait for both calls within the same function without nesting them or waiting for the first call to finish before calling the second one?

Answer №1

One possible approach could be to utilize the $when method in the following manner: $.when(action1, action2).done(() => {}). However, it is essential to ensure that both function1 and function2 are properly defined with deferred functionality.

Answer №2

  1. In my opinion, utilizing the
    $q.all([promise1, promise2, promise3]).then()
    syntax would be most effective in your scenario.
  2. It seems that you are invoking msGraph.getClient() multiple times; this repetition may be unnecessary.

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

How can I use CSS to ensure that both cards and images are equal in size?

I am currently utilizing react, with Material-ui being used for the Cards. For the layout, I have implemented CSS Grid Layout for the Grid system. Presently, the structure looks like this: https://i.stack.imgur.com/0FDyY.png However, my desired outcome i ...

Tips for creating a responsive Livewire Pagination system

Looking to make Livewire pagination responsive? When using Bootstrap, simply add flex-wrap to the pagination class to ensure responsiveness. Component: class Index extends Component { use WithPagination; protected $paginationTheme = 'bootstr ...

Utilize .map function to format a date string and generate a table

I am currently utilizing .map along with React in order to generate a table using a coupons object. My goal is to format a date string into the "mm/dd/yyyy" format, with coupon.starts_at typically being set as coupon.starts_at = "2013-08-03T02:00:00Z" I h ...

"Resetting the state of a form in AngularJS2: A step-by

Looking to reset the form state from dirty/touched in angular? I am currently delving into the world of angular2 and working on a form with validation. In my journey, I came across this code snippet: <form *ngIf="booleanFlag">..</form> This ...

Using Vue.js to display svg content inside the <svg> element

One of my Vue.js components is responsible for dynamically building the content of an svg element. Let's simplify things and say that the content consists of a <circle cx="50" cy="50" r="60" /> This component achieves this by manipulating a dat ...

Linking a pair of checkboxes

I am dealing with two checkboxes on my website. <input class="checkbox1" type="checkbox" name='1' id="example1" value="example1"/> and <input class="checkbox2" type="checkbox" name='2' id="example2" value="example2"/> I ...

I need to verify that the input type for time is valid, starting from today's date and extending beyond the current

<input type="date" onChange={(e)=>setDate(e.target.value)}/> <input type="time" onChange={(e)=>setTime(e.target.value)} /> If the selected date is after today and the time is after the current time, display a valida ...

Access the content of each cell in a table using JavaScript

I need help with a scenario involving a table that has 4 rows, where the 4th row contains a textbox. When the "onchange" event of the textbox is activated, I want to retrieve the data from the cells in that specific row and transfer it to another table. It ...

Finding solutions using a controller class

I have a component that uses a controller class and accepts an input parameter through the use of a bindings object. In the controller, I am able to access the parameter after the constructor runs, but I cannot pass it as a constructor parameter. While wo ...

Unable to retrieve data from AJAX request in the AJAX success function

I've seen this question asked multiple times and I've gone through several answers regarding callbacks, but I'm still struggling to understand how to apply it to my specific situation. I have an ajax function that is being called from the su ...

How to implement a "callWhenReady" function in JavaScript

I am new to javascript and currently working on restructuring my prototype code. The current setup involves multiple levels of nested callbacks, making it difficult to read and manage. I am aiming for a cleaner approach similar to the following: GoogleMap ...

How to create a dropdown menu in React js with an array of items

Can we structure the array without splitting it into two parts and iterating over them? arrayList=[Jeans, Jackets, Pants, Fragrance, Sunglasses, Health Products] <div className='Flexbox'> //arrayList1.map](//arrayList1.map)(x=>return(< ...

Delay the execution of the function in AngularJS until the browser has finished rendering completely and the view-model synchronization cycle has ended

I'm uncertain about the appropriate title for this inquiry, so please correct me if I am mistaken. Suppose that upon page refresh (load), I require an animated scroll to an anchor based on the current location's hash (I am aware of ngAnchorScrol ...

boosting the maximum number of requests allowed

What can be done to increase the request limit if the user continues to hit rate limits? This is my current rate limiter setup: const Limiter = rateLimit({ windowMs: 10000, max: 5, standardHeaders: true, legacyHeaders: false, keyGenerator: funct ...

Having a hard time finding the perfect styling solution for Material UI

Is there a way for me to customize the styling of Material UI's components in addition to their default rules by injecting my own CSS? I'm unsure how I would go about setting these parameters using the styled-components API. Is this even doable? ...

React textarea trigger function on blur event

https://codesandbox.io/s/react-textarea-callback-on-blur-yoh8n?file=/src/App.tsx When working with a textarea in React, I have two main objectives: To remove focus and reset certain states when the user presses "Escape" To trigger a callback function (sa ...

Repeated module imports

Currently, as part of my app development process, I am utilizing Parcel along with @material-ui/styles. One crucial aspect to note is that my app has a dependency on the @material-ui/styles package. Additionally, I have incorporated my own npm package, sto ...

How can I specify the exact width for Bootstrap 3 Progress Bars?

I have a single page that displays all my files in a table format, and I also have the count of open and closed files. My goal is to represent the percentage of closed files using a progress bar. The width of the progress bar should change based on this p ...

Switching the body's background image dynamically using javascript

I'm attempting to switch up the background image using JavaScript. Here's how I've defined the background: body { background: black; overflow-x: hidden; overflow-y: hidden; } body:before { overflow-x: hidden; overflow ...

What could be causing my div to not appear when using jquery's show function?

I'm dealing with HTML code that looks like this: <div id="answerTypeSection" style="visibility: hidden"> <div class="row"> <div class="col-md-2">adfadfafasdfasdfas</div> </div> <label class="control-label"&g ...