AngularJS + Asynchronous Operations

I'm working with AngularJS and I have two API methods in my factory. I've been trying to call these two methods one after the other, but it's not functioning as expected.

The desired sequence is to first execute test1 followed by test2.

Below is the code snippet from the controller:

app.controller("Test").function($scope, factoryMethod) {
    factoryMethod.test1().then(function(data) {

        console.log(data);
        console.log("test1");

    }).then(factoryMethod.test2().then(function(data) {
        console.log(data);
        console.log("test2");

    })).catch(function(data) {
        alert(data);
    });
}

And here's the relevant part from the factory:

app.factory("factoryMethod", function (){
    //code for test1 
    //code for test2
});

At the moment, the console output shows: 1. test2 2. test1

The expected behavior is to log test1 first, followed by test2.

Answer №1

Here is an example of how it can be achieved using the code snippet below:

var app = angular.module('myapp',[]);

app.factory("factoryMethod",['$q',function($q){
  
  var  test1 = function(){
     var deferred = $q.defer();
    
         deferred.resolve("test1");
          
          return deferred.promise;
    }
    
  var  test2 = function(){
      var deferred = $q.defer();
    
         deferred.resolve("test2");
          
          return deferred.promise;
    }
    
  return {
      test1 : test1,
      test2 : test2
    }
}]);

app.controller("Test",function($scope, factoryMethod){
  
  var promise =  factoryMethod.test1();
  
  promise.then(function(data){
  
    console.log(data);
    
    factoryMethod.test2().then(function(data){
    console.log(data);
        },function(error){
    console.log("error from test 2");
})
      },function(error){
   console.log("error from test 1")
})
   
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp" ng-controller="Test">
  
</div>  

Answer №2

app.controller("Practice").resolve($scope, factoryService) {
    factoryService.testA().then(function(info) {
        console.log(info);
        console.log("testA");
        factoryService.testB().then(function(info) {
            console.log(info);
            console.log("testB");
        });
    }).catch(function(info) {
        alert(info);
    });
}

Answer №3

app.controller("Test").function($scope, factoryMethod) {
    var myData = factoryMethod.test1().then(function(data) {

        // Retrieve data from factoryMethod1
        return data;

        // Alternatively, retrieve data from factoryMethod2 (if you want this, remove the previous return statement)
        return factoryMethod.test2().then(function(data) {

            return data;
        });
    }).catch(function(errorData) {
        alert(errorData);
    });
}

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

Steps to resolve the error "Cannot POST /index.html" in Nginx, Express, and NodeJS

While setting up my MERN project on the production server, I encountered an issue. In order to manually type in URLs (like myproject.com/dashboard), I added the line try_files $uri /index.html; to the server section of my Nginx configuration file as recomm ...

Show or hide a div in Vuejs based on checkbox selection

I've been attempting to toggle the visibility of a container div using Vuejs with no success. I've tried two different methods, but neither seem to work for me. Here is Method 1: <body> <div class="checkbox" id = "selector"& ...

Discover the method for creating internal links on a single page with AngularJS

What is the best way to create internal links using angular js? In html, we typically use <a href="#top">Top</a> to navigate to an element with the id "top". ...

Using Sweetalert2 to send data via AJAX POST request

Recently, I've been incorporating SweetAlert2 into my project and I want to create an "Add Note" feature. The process involves the user clicking a button, being directed to a page, and then the following script is executed: <script>swal({ ...

As I go through the database, I notice that my div model functions correctly for the initial record but does not work for any subsequent ones

I came across a model on w3 schools that fits my requirements, but I am facing an issue where the model only works for the first result when looping through my database. It's likely related to the JavaScript code, but I lack experience in this area. C ...

The JavaScript event responsible for reloading the page is triggering every time the page is refreshed, resulting in an endless loop

Initially, the issue does not arise, however, it only occurs when the event is triggered by reordering the column, causing an automatic reload afterwards. tabelaProdutos.on('column-reorder', function(e, settings, details) { ... location ...

Could the issue with jQuery selector potentially be connected to AngularJS?

Integrating a third-party web page into an Android webview in our app presents the challenge of automating the login process. Since the app has access to the login credentials for the third-party site, I'd like to execute some Javascript for this purp ...

Issues with CSS Modules not applying styles in next.js 13 version

Employing next.js 13.1.1 along with /app Previously, I had been handling all of my styles using a global.css, however, I am now attempting to transition them into CSS Modules. Within my root layout.js, there is a Header component that is imported from ./ ...

The DOM does not contain unscrolled rows in the DataTable's infinite scrolling feature

Every time I create a dataTable with infinite scrolling, I use the following code: $('#table1').dataTable({ 'aaData' : dataArr, 'aoColumns': columnArr, 'bScrollInfinite': true, 'bColumnCollapse& ...

AJAX Triggering fopen Function

In the process of developing a WebApp, I have a requirement to use AJAX to send both text content and a filename to a PHP script located in the same directory as the JavaScript source code. The ultimate goal is to have the PHP script save the file on the ...

Identify the page search function to reveal hidden content in a collapsible section

Our team has implemented an expandable box feature on our wiki (in Confluence) to condense information, using the standard display:none/block method. However, I am looking for a way to make this work seamlessly with the browser's find functionality. S ...

Maximizing the use of JavaScript's prototype.js library: Passing parameters to callback functions

My understanding of JavaScript is limited to using it for Dynamic HTML. However, I am now exploring Ajax and facing an issue with the code below (taken from and modified to suit my requirements). I need to pass the update_id parameter to the onSubmit fun ...

What is the best way to utilize JSON data in React components?

I am looking to showcase a collection of icons similar to what I saw on this particular website. Within my JSON data, I have stored both the family and name values for these icons. What I aim to do is map this JSON data in order to pass the family and nam ...

Reorganize components in MongoDB record

Description: Each customer object includes a name field. A line object is comprised of the following fields: inLine - an array of customers currentCustomer - a customer object processed - an array of customers The 'line' collection stores doc ...

Automatic line breaks in MathJax when displayed in a modal dialogue box

As part of a math project, I need to display the solution of a problem in a Sweetalert2 modal. However, despite using the following code: <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: { inlineMath: [['$','$ ...

Don't let noise linger in the background unnoticed

Within my HTML table, there are 32 cells that each possess an onclick="music()" function. This function is currently functioning correctly, with one small exception. I desire for the functionality to be such that whenever I click on a different cell, the m ...

How can I optimize the usage of npm as a front end package manager in my Node.js application?

As I delve into learning Node.js and Express, my goal is to incorporate Angular for the frontend. While I am comfortable using npm for managing Node.js modules, I am facing a dilemma when it comes to handling frontend dependencies. Most tutorials suggest u ...

Instructions on utilizing the CSSStyleSheet.insertRule() method for modifying a :root attribute

Is it possible to dynamically set the background color of the :root CSS property in an HTML file based on a hash present in the URL? The code provided does change the background color, but unfortunately, the hash value doesn't persist as users navigat ...

Positioning pop-up windows using Javascript and CSS techniques

In my web application, there is a search field that allows users to enter tags for searching. The window should pop up directly below the search field as shown in this image: Image I am trying to figure out how the window positioning is actually d ...

Tracking current page path changes with UI-router for Google Analytics

I am currently facing challenges in obtaining the path of the state to be sent to Google Analytics. The use of abstract states complicates this process, as using something like toState.url does not capture the entire URL. My initial approach was to utiliz ...