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!