$ http.get中的随机响应序列 [英] Random sequence of response in $http.get
问题描述
我正在尝试编写一个函数,该函数根据 idArray
中的ID数向服务器发送多个请求.我面临的问题是,被推入 dataArray
的数据未遵循 idArray
的相应ID的正确顺序.我尝试将 timeout
添加到HTTP请求中,以便在 for
循环的下一次迭代之前完全处理先前的请求,但这似乎也不起作用.请帮忙.
I'm trying to write a function that sends multiple requests to the server based on the number of Ids in the idArray
. The problem I'm facing is that the data that is pushed into the dataArray
does not follow the proper sequence of the corresponding Ids of the idArray
. I tried adding the timeout
to the HTTP requests so that the previous request is fully processed before the next iteration of the for
loop, but that too does not seem to work. Please help.
function commonService($http, $q) {
return {
getAboutContent: function() {
var dataArray = [];
var deferred = $q.defer();
var idArray = ['about2', 'about3'];
var count = 0;
angular.forEach(idArray, function(id) {
$http.get('server url/' + id).success(function(data) {
dataArray.push(data);
count++;
if (count == idArray.length) {
deferred.resolve(dataArray);
}
}).error(function(error) {
console.log('error', error);
deferred.reject(error);
});
});
return deferred.promise;
}
}
}
推荐答案
您不能确定地说第一个AJAX调用将首先完成,因为这是异步调用.因此,如果使用 for
循环进行3次调用,则无法保证响应的顺序相同.因此,假设您可以从服务器AJAX调用返回 id
,则可以这样编写:
You can not say with surety that the first AJAX call will be completed first as that is the asynchronous call. So if you are doing 3 calls using your for
loop you can not guarantee that the response will come in the same order. So, assuming you can return the id
from the server AJAX call then you can write like this:
function commonService($http, $q) {
return {
getAboutContent: function() {
var dataArray = [];
var deferred = $q.defer();
var idArray = ['about2', 'about3'];
var count = 0;
angular.forEach(idArray, function(id) {
$http.get('server url/' + id).success(function(data) {
// Return the "id" from the response and get the index position in the "idArray"
var idIndex = idArray.indexOf(data.id);
// Then insert data into the specific index as of "id"
dataArray[idIndex] = data;
count++;
if (count == idArray.length) {
deferred.resolve(dataArray);
}
}).error(function(error) {
console.log('error', error);
deferred.reject(error);
});
});
return deferred.promise;
}
}
}
这篇关于$ http.get中的随机响应序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!