AngularJS: handling multiple asynchronous requests

When I make multiple ajax calls in my code, I noticed that the API is only reached after all the ajax calls have been executed.

Below you can see the JavaScript code:

 function test = function(){
        var entity = {};
        entity.Number = 1;
        appFactory.testPostCall(entity, 'ApiController/TestMethod');

        entity.Number = 2;
        appFactory.testPostCall(entity, 'ApiController/TestMethod');
    }

The AppFactory looks like this:

factory.testPostCall = function (number, appendUrl) {
        var q = $q.defer(); 

        $http({
            method: "POST",
            url: url + appendUrl,
            data: number
        }).success(function (data, status, headers, config) { 
            q.resolve(data);
        }).error(function (data, status, headers, config) {
            q.reject(data); 
        });
        return q.promise;
    }

For the API part:

[HttpPost]
        public Nullable<int> TestMethod(TestEntity entity)
        {
           return entity.Number;
        }

As I traced how the code runs using breakpoints, calling the test() function executes the following:

 Javascript -> AppFactory
Javascript -> AppFactory
API
API 
//with the parameter Entity having the value Entity.Number = 2 for both API calls.

I tried putting a breakpoint at

entity.Number = 2; 

and waited until the API was called, but it seems like the code waits for the function to finish before making the API call. This behavior has confused me, as I expected something like this:

Javascript -> AppFactory -> API //entity.Number = 1

Javascript -> AppFactory -> API //entity.Number = 2

Chaining works well, but I want to run both independently and understand what's happening.

    entity.Number = 1;
            appFactory.testPostCall(entity, 'ApiController/TestMethod')
.then(function(data){
            entity.Number = 2;
            appFactory.testPostCall(entity, 'ApiController/TestMethod');
    }); 

Thank you!

Answer №1

When passing the entity to your function in both guesses, it's important to note that in JavaScript, objects are passed by reference and not by copy. This concept has been discussed on Stack Overflow multiple times: Why isn't this object being passed by reference when assigning something else to it?

To achieve the desired behavior, there are two options available:

  • You can utilize a closure to ensure that the parameter is passed as intended.
  • You can make a shallow copy of your object.

Alternatively, I would suggest considering a third approach, which involves not simply passing an object to your API without careful consideration.

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

Learn how to implement a jQuery plugin within an AJAX request

Issue with PHP website: Trying to display an image on button click within the same webpage using an imageViewer effect. Currently, the image opens in a different webpage. Any help with code snippet would be greatly appreciated. Thank you! <script type= ...

Instantly see changes without having to manually refresh the screen

I need help figuring out how to update my PHP webpage or table automatically in real-time without requiring a manual refresh. The current functionality of the page is working perfectly fine. Specifically, I want the page to instantly display any new user ...

Adding flair to a fresh element and then removing it upon its inception

I'm working with a JavaScript code that creates a new element when a button is clicked. I have a question about it. Here's the JavaScript code snippet: var comment = document.querySelector("#AddComment"); var req = new XMLHttpRequest(); if(comm ...

Router failure resulted in an internal server error

When navigating to a page in my router, I make a REST API request to retrieve data from the server in the beforeEnter clause as shown below: beforeEnter: (to, form, next) => { getData().then( (response) => { ...

Two distinct iterations of the identical jquery version sourced from external sources

NOTE: This situation involves having two copies of jQuery with the same version number but different libraries loaded by external sources. This is distinct from the issue of using multiple versions of jQuery on a single page, as discussed here: Can I use m ...

Windows devices are connecting with web-based services

Can a Windows Gadget be developed to interact with a web service? In this scenario, the web service would call a pre-defined SQL Server query and return the results. If this is possible, what would be the best way to approach it? Has anyone attempted or ...

Trouble with NodeJS NPM

I'm encountering difficulty when trying to install npm packages. npm ERR! Windows_NT 6.3.9600 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules&bso ...

Choose a specific parameter from a line using the body parser in Node.js

Upon receiving a post message, I am having trouble selecting a value from CSV data. Here is a sample of what I receive: { reader_name: '"xx-xx-xx-xx-xx-xx"', mac_address: '"name"', line_ending: '\n', field_delim: & ...

I will receive a 404 error if I try to access a URL without including the hashtag symbol

Is it feasible to display a record by directly inputting the user ID in the URL without using the # symbol? I am currently working on a website where I have a single view page named Login.html. I want to be able to access this page by entering the user&ap ...

What is the process for setting up a new router?

When it comes to templates, the vuestic-admin template from https://github.com/epicmaxco/vuestic-admin stands out as the perfect fit for my needs. However, I have a specific requirement to customize it by adding a new page without displaying it in the side ...

The "disabled" attribute is no longer recommended, please utilize "disable" instead

Lately, after upgrading AngularJS, I have been receiving a warning whenever I open a ui.bootstrap modal. The warning in Chrome-beta 44 says: angular.js:11655 Use of "disabled" attribute has been deprecated, please use "disable" I'm curious if this i ...

When communicating with the backend in a React application, the data is not being successfully sent using axios. An error message stating "Unsupported protocol

My current setup involves using Express.js as the backend and setting up a proxy to the backend in the package.json file of my React.js project. Initially, I encountered an error when using the fetch method, so I switched to using Axios to resolve this iss ...

Updating materials within the Forge

Currently, we have implemented a system where the client retrieves object states when the page loads, changing the colors of 'pending' objects in the model. We continue to poll for changes to update the coloring - initially coloring pending objec ...

ReactJS is in need of extracting certain values from a promise

Within my Firebase database, I have organized data into two Documents: "users" and "posts". Each post in the "posts" collection is linked to a specific user using their unique id from the "users" collection. My goal is to retrieve user data associated wi ...

Unexpected state being returned by Vuex

I am encountering an issue with a pop-up modal that is not behaving as expected. The condition for the pop-up to appear is if the user has no transactions, which is determined by checking the length of the depositHistory array. If the length is greater tha ...

When using Mongoose's save function within an async.each loop, it may

While working on an array processing task that involves saving and validating data asynchronously, I encountered an issue with duplicates. Here is the data I'm currently processing: var guests = [{ "email": "<a href="/cdn-cgi/l/email-protection" ...

Manipulating the .innerHTML property allows for selectively replacing sections

In my JavaScript code, I am trying to display a video along with a countdown timer. Once the countdown finishes, it should switch the content of the div to show a question. Below is my current implementation: <script type="text/javascript"> ...

Changing the Value of an Input Element Dynamically in React: A Step-by-Step Guide

In a scenario where I have a component that takes an element, such as <input />, and I need to update its value programmatically after 15 seconds. Initially, I had the following approach in mind: const MyComponent = (myInput: JSX.Element) => { ...

Utilize JavaScript to activate a new browser tab and monitor its status for closure

When I attempt to open a new tab using JavaScript and track when it is closed, none of the events are being triggered. All the examples I found reference the onbeforeunload event for the current window, not for other window objects. window.addEventListe ...

Addressing memory leaks in React server-side rendering and Node.js with setInterval

Currently in my all-encompassing react application, there's a react element that has setInterval within componentWillMount and clearInterval inside componentWillUnmount. Luckily, componentWillUnmount is not invoked on the server. componentWillMount( ...