Angular Promise not executing in a synchronous manner

In the javascript controller, I have a code snippet that consists of two separate functions. While these functions work individually and asynchronously when triggered from the view, my goal is to execute them synchronously on page load. This is necessary because the output of the first function is utilized as input for the second function.

$scope.function1= function () {
    $http({
        url: '/Class/method1/',
        method: 'GET'
    }).success(function (data) {
        $scope.mygrid= data.data;
        $scope.myvalue= $scope.mygrid[0];
    });
};

$scope.function2= function () {
    $http({
        url: '/class/method2/',
        method: 'POST',
        params: { myValue: $scope.myvalue }
    }).success(function (data) {
        $scope.myValue2 = data.data;
    });
};

 var initialize = function () {
    var defer = $q.defer();
    defer.promise
        .then(function() {
           $scope.function1();
        })
        .then(function() {
           $scope.function2();
        })
defer.resolve();
  }; 
initialize();

However, during the execution of the second function call, the value of $scope.myvalue becomes null even though data was returned from function one. My suspicion is that function2 might be getting called prematurely. Could someone provide some guidance on this? :-)

Answer â„–1

The process within the initialize function occurs synchronously, unlike the asynchronous nature of $http requests. This leads to a situation where $scope.function2 is executed without waiting for a promise in $scope.function1 to be fulfilled.

A better approach would involve:

$scope.function1 = function () {
    return $http...
};

$scope.function2 = function () {
    return $http...
};

In this scenario, using a deferred promise like the deferred anti-pattern would not be recommended. The initialize function should be concise and structured as follows:

 var initialize = function () {
    return $scope.function1().then(function() {
           return $scope.function2();
    })
  }; 

Answer â„–2

$http({
        url: 'different-url',
        method: 'GET'
    })

Furthermore, this can be considered a promise, so it will execute asynchronously.

$scope.myFunction= function () {//3rd action
    $http({
        url: '/NewClass/method/',
        method: 'GET'
    }).success(function (data) {
        $scope.newGrid= data.data; //this executes asynchronously after receiving the response
        $scope.value= $scope.newGrid[0];
    });
};

$scope.anotherFunction= function () { //5th action
    $http({
        url: '/newclass/method2/',
        method: 'POST',
        params: { newValue: $scope.value }
    }).success(function (data) {
        $scope.repValue = data.data; //this executes asynchronously after receiving the response
    });
};

 var start = function () {
    var defer = $q.defer();
    defer.promise
        .then(function() {
           $scope.myFunction(); //2nd action
        })
        .then(function() {
           $scope.anotherFunction(); //4th action
        })
defer.resolve(); //1st action
  }; 
start();

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

Can you create a dynamic visual display using HTML5 Canvas to draw lines in a circular pattern that react

I have successfully implemented drawing lines around a circle using the AudioContext API. However, I am facing an issue with the lineTo function, as the line only grows and does not shrink. My inspiration for this project comes from the audio visualizer fo ...

Is it possible to use function declaration and function expression interchangeably?

As I dive into learning about functions in Javascript, one thing that's causing confusion for me is the difference between function declaration and function expression. For example, if we take a look at this code snippet: function callFunction(fn) { ...

The URL in React Router updates as expected, but when attempting to render a component using a button component link

I have encountered a situation similar to the one portrayed in this CodeSandBox example, where I am required to implement react routing within two distinct components. The issue that is perplexing me is that, when I navigate down to either the Profile or ...

Why is my res.data returning an array of objects in AngularJs?

I've been working on integrating an API with AngularJS and trying to display the data using ng-repeat, but I'm facing challenges in accessing the object's information. Below is the feedback I received: (20) [{…}, {…}, {…}, {…}, {†...

Unveil the modules of a Node.js NPM application

I have a Node application that is used as an npm module and serves as a dependency in the package.json file of another Node application. This application needs to grant access to internal modules to the app utilizing my package as a dependency. All these m ...

Updating AngularJS scope does not occur when a value is selected using jQuery

When writing a test using cucumber and selenium, I encountered an issue with a dropdown selection. After selecting a value using jQuery, pressing next resulted in an error. The problem seems to be that Angular has not updated its scope properly. <sele ...

Discovering an HTML Element in a JavaScript Array with Specific Styling: A Step-by-Step Guide

I am in the process of developing a website that consists of different sections. The concept is simple - by clicking on a button located at the bottom of the page, it will reveal the corresponding div section. For styling purposes, I have initially hidden ...

What is the best way to retrieve JSON key/value pairs instead of an array?

I am working on retrieving data from a Google Spreadsheet using App Script and have set up a DoGet function. Currently, I am getting an array of data but I need it in JSON key-value pairs format. The table in my Google Sheets is structured as follows: Th ...

Unleashing the power of React: Integrating raw HTML <a href> tags with JavaScript

I am currently working on a small web app that mimics browsing WikiPedia by fetching raw HTML content of WikiPedia articles through its API. I then display this HTML in my app using "dangerouslySetInnerHTML". I am faced with the challenge of enabling a us ...

Jumping Iframe Anchor Link in Src

I'm facing a challenge with an iframe positioned in the center of a webpage. I want to show content from another page within the iframe, but not starting at the very top. To achieve this, I inserted an anchor into the src of my iframe, linked to an a ...

What is the best way to divide my Vue.js project into separate sections for development and testing purposes?

I am looking to split my vuejs frontend project into two sections: development and testing. For the development section, I want to work locally and make requests to the example:8010 url, while for the testing section, I need to send requests to the example ...

Tips on accessing the returned value from the controller within a JSP page using Ajax

This is a snippet of my JavaScript code: <script type="text/javascript"> function callMe() { var districtId = $("#district").val(); alert(districtId); $.ajax({ type: "POST", ...

Adjust an UpdatePanel with client-side code triggering server-side operations

I am fairly new to asp.net and have been experimenting with it for around a week now. Currently, I have a page that interacts with a web service, continuously checking its progress (shown in an UpdatePanel) until completion. Once the process is completed, ...

Sending a Form Generated in Real Time with a Button Located Outside the Form

I'm currently working on a feature that allows users to add multiple invoices on a single page. Users can click on a link to display the invoice fields in a modal form, which is dynamically generated using AJAX. Once the user has filled out the requi ...

Having difficulty retrieving objects within a foreach loop of object keys that do not meet the criteria of the string.prototype.replace method

Currently, I am working on looping over objects within a key:value array in JavaScript to use the string.prototype.replace method for paths to JS files in GulpJS concat tasks. The objective is to generate a list of paths that GULP can utilize, but they re ...

Chat application using Node.js without the need for Socket.IO

Recently delving into the world of Node.js, I stumbled upon the fs.watchFile() method. It got me thinking - could a chat website be effectively constructed using this method (along with fs.writeFile()) in comparison to Socket.IO? While Socket.IO is reliabl ...

How can Ext JS 6.2 automatically expand the East panel when the West panel is triggered?

In my Ext JS v6.2 Grid application, I am faced with the task of ensuring that if the WestRegion panel is closed, the EastRegion panel should open automatically, and vice-versa. Being new to Ext JS, I initially attempted to achieve this using jQuery. Howeve ...

ng-include failing to retrieve file name containing UTF-8 character

I encountered an issue with the ng-include directive in the code snippet below. The file name it's trying to access contains a special character, specifically an ñ, resulting in a not found error being displayed. <div ng-include="'{{mainCtrl ...

Placing a new item following each occurrence of 'X' in React components

Currently, I am working with a React component that uses Bootstrap's col col-md-4 styles to render a list of items in three columns. However, I am facing an issue where I need to add a clearfix div after every third element to ensure proper display of ...

Choosing an element in Protractor based on an HTML attribute value that contains a specific text

Having trouble figuring out how to target an element that lacks a standard unique id or class. How can I locate this input element using Protractor? Please note that I am unable to use the ComboBoxInput_Default class because it is shared across multiple p ...