How can I manage two asynchronous calls simultaneously in AngularJS?

Exploring the world of promises in AngularJS, I am facing a challenge with nested asynchronous functions.

The scenario involves one asynchronous function calling another asynchronous function upon success. The goal is to execute certain operations only after both functions have completed their tasks.

// Inside Controller    
         ServiceName.AsyncFunc1().then(function(){
               alert("Complete");     
         })


// Inside Service    
            app.service('ServiceName', function ($http) {
            return {
                AsyncFunc1 : function()
                {
                       var self = this;
                       return $http.post(url).
                       success(data)
                       {
                            self.AsyncFunc2();
                       }
                },
                AsyncFunc2 : function()
                {
                       return $http.post(url2).
                       success(data)
                       {
                            alert("AsyncFunc2 Complete");
                       }
                },
          }
    });

My aim is to trigger alert("Complete") only when both asynchronous calls have finished executing sequentially. However, currently the alert("Complete") appears before alert("AsyncFunc2 Complete").

Answer №1

In the event that you desire your alert notifications to be triggered when both functions return a promise, consider utilizing $q.all

The usage of $q.all mandates an array of promises.

For instance:

 $q.all([function1(), function2()])

UPDATE Understood! In that scenario, you can simply use 'then' after the completion of the second sequential function. Based on your explanation, this is my understanding.

(function(){
  angular
    .module('myApp')
    .controller('MyController', MyController);


  function MyController(myService) {

    function secondASyncSuccess() {
      alert("The second function has been completed");
    }

    function firstFuncSuccess() {
     alert("First function complete");
      myService.secondASyncFunction()
        .then(secondASyncSuccess, secondASyncFailure);
    }

    myService.firstASyncFunction()
      .then(firstFuncSuccess, firstFuncFailure);
  }

})();

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

The dimensions on Next.js pages exceed those of the viewport by a significant margin

I have recently encountered a perplexing issue where the dimensions of my webpage appear to be 2.7 times larger than the viewport, even when there is no content or styles applied. The strange part is that it seems as though the page has been scaled up, eve ...

Transferring the dirty state of the view to the parent form

Within my main form's markup, there is a specific structure that includes a tabset and a selectView method in the controller: <tabset vertical="true" type="pills"> <tab ng-repeat="tab in tabsViews" sele ...

What is the functionality of named function expressions?

After coming across an intriguing example in the book labeled as a "named function expression," I was curious to delve into its mechanics. While the authors mentioned it's not commonly seen, I found it fascinating. The process of declaring the functi ...

Adjust the size of child divs in relation to their parent divs using jQuery

I am working with 4 divs and trying to adjust the size of the inner divs in relation to the parent divs dynamically. I have added a .top class, but I'm unsure if it is necessary or beneficial. Here is my fiddle for testing purposes: http://jsfiddle.n ...

Can you please explain why I am unable to remove the item in my code using Node.js and Express?

Currently, I am in the process of learning NodeJS and working on an application that involves adding Bicicleta objects. However, I have encountered an issue where I am unable to delete these objects successfully. Even though the POST request for deletion r ...

Creating an overlay-section in three.js with orbit-controls that dynamically responds to the main view's movement

I'm looking to incorporate a section in the corner of my main view that displays a miniature version of the main view. Currently, I am developing a webpage using JavaScript with three.js. The main view window showcases various geometries that can be ...

When utilizing Nettuts' CSS navigation resource, the bottom shadow will disappear if the parent element contains child elements

I'm currently working on customizing a solution I stumbled upon on Nettuts to fit my specific requirements. Everything seems to be functioning well, except for a peculiar issue I'm encountering while hovering over a top-level navigation element t ...

Error message stating that module 'html' cannot be found while trying to access an HTML webpage

Upon starting my application and navigating to localhost:8333 in my browser, an error was thrown: Error: Cannot find module 'html' at Function.Module._resolveFilename (module.js:338:15) at Function.Module._load (module.js:280:25) at Module. ...

Sort items into two arrays based on a common value

I'm struggling to group items from one array based on a value from another array, but I can't seem to figure out the right approach. In my orders array, each object has a key-value pair like id: 999324. Now, in another array for products, there ...

When using React, I have successfully saved my data in LocalStorage using JSON, but I am facing issues retrieving it upon reloading the page

After successfully converting the data item into JSON format, I faced an issue where upon reload, the item would reload but always ended up being rewritten. This led to a red line appearing under the (localStorage.getItem('chatLInes')) part accom ...

Concealing a vessel, refreshing the innerHTML content, and then revealing it once more

Is it possible to conceal a container, modify the innerHTML of said container, and then reveal the container again? It appears that accomplishing both actions simultaneously is proving to be tricky... For a visual example, check out this JSFiddle - https: ...

Struggling to execute a basic Typescript file

I recently embarked on a journey to learn Typescript by enrolling in this specific course. The process of setting up everything seemed simple enough. I created a new directory, executed the command npm init, and followed it up with npm install --save-dev t ...

What is preventing the function from waiting for the promise to be resolved?

I am encountering an issue with the code snippet below. The control does not wait for the HTTP promise to be resolved before returning a string from the method, and I can see that the returned object is "method" in the switch statement. Can someone please ...

Retrieve the ngModel's current value within the ngChange event handler

Is there a way to access the viewValue of an input with ngModel inside an ngChange function? <input type="text" ng-model="getMyObject().value" ng-change="insert(1, 'my object property')" /> I attempted: <input type="text" ng-model="ge ...

Identify numbers and words within a sentence and store them in an array

Looking to split a string into an array based on type, extracting numbers and floats. The current code is able to extract some values but not complete. var arr = "this is a string 5.86 x10‘9/l 1.90 7.00" .match(/\d+\.\d+|\d+&bsol ...

Differences Between DOM and Refs in React

When it comes to React, what distinguishes the use of DOM from Refs? While it is possible to utilize typical JavaScript DOM node selectors in React for targeting specific elements, refs also offer a way to achieve the same functionality. What are the adv ...

Load Bootstrap tab activation

I'm having trouble getting the active class to work on my tabs. I've tried using body onload click trigger, showing tabs by ID, and many other methods, but nothing seems to be working. I have implemented hashed URLs to allow for individual tab li ...

The FlatList component with a specified number of columns is failing to display the desired

Hey guys, I have a food list data stored in JSON format as shown below: [ { "id": 0, "key": " Viande hachee", "checked": false, "image": "https://i.imgur.com/RuVD8qi.png " }, { "id": 1, "key": " Escalope pane", "check ...

Utilizing Regular Expressions in an Express.js Router

Looking for documentation on regex in Express has led me to discover that the information in the Express API is quite minimal. Currently, I am experimenting with a regex matching objectID example provided in the Express documentation. router.get(/^\/ ...

Issue with disabling elements using jQuery in IE 10

I'm encountering a problem with using attr('disabled', 'disabled') or prop("disabled", true) in Internet Explorer when using jQuery. This works fine in Firefox and Chrome but not in IE. Any suggestions? I'm attempting to disa ...