AngularJS : multiple asynchronous AJAX calls

I am calling multiple ajax calls but the code only reaches the API after all the ajax calls are executed.

Javascript:

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

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

AppFactory

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;
    }

API

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

I traced how to code runs by breakpoints. calling 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 placing a breakpoint at

entity.Number = 2; 

and wait till the API is called but it seems that the code is waiting for the function to end until the API is called. I am so confused on the behavior of this, I am actually expecting something like the following:

javascript -> appFactory -> API //entity.Number = 1

javascript -> appFactory -> API //entity.Number = 2

Chaining works well but I need to run both independently and I really want to understand whats happening.

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

Thank you!!!

Upvotes: 0

Views: 191

Answers (1)

S&#233;bastien Renauld
S&#233;bastien Renauld

Reputation: 19672

You're passing entity to your function in both guesses. Guess what? In JS, all objects are passed by reference and not by copy. Similar questions are all over SO: Why isn't this object being passed by reference when assigning something else to it?

You have two possibilities to have the behaviour you expect:

  • You can use a closure to make sure that the parameter is passed as you would like
  • You can shallow-copy your object

I would personally go towards a third option, however, which consists in not blindly passing an object to your API.

Upvotes: 1

Related Questions