我正在调用多个ajax调用,但代码只在执行了所有ajax调用后才到达API。
使用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;
}
我追踪了如何通过断点编码运行。调用test()函数执行以下操作:
javascript -> appFactory
javascript -> appFactory
API
API
//with the parameter Entity having the value Entity.Number = 2 for both API calls.
我尝试在
处放置一个断点entity.Number = 2;
并等到API被调用,但似乎代码正在等待函数结束,直到调用API。我对此行为非常困惑,我实际上期待以下内容:
javascript -> appFactory -> API //entity.Number = 1
javascript -> appFactory -> API //entity.Number = 2
链接运作良好,但我需要独立运行,我真的想了解发生了什么。
entity.Number = 1;
appFactory.testPostCall(entity, 'ApiController/TestMethod')
.then(function(data){
entity.Number = 2;
appFactory.testPostCall(entity, 'ApiController/TestMethod');
});
谢谢!!!
答案 0 :(得分:1)
在两次猜测中,您都会将entity
传递给您的函数。你猜怎么着?在JS中,所有对象都是通过引用传递的,而不是通过复制传递的。类似的问题都在SO上:Why isn't this object being passed by reference when assigning something else to it?
您有两种可能获得预期的行为:
我个人会选择第三种方法,但不是盲目地将对象传递给API。