Javascript For循环未正确执行http服务
我试图通过一个函数(callAPI)调用for循环中的http服务。 这是我的密码。我在这段代码中遇到的问题是,当http服务赶上时,我没有以正确的顺序调用正确的id。在callAPI函数上,它在运行一个http服务异步请求之前,会遍历console.log(id)的所有调用,然后它运行http服务调用,但id的顺序错误。例如,我返回了一个数组[6,6,3],它按[3,6,6]的顺序运行。感谢您的帮助Javascript For循环未正确执行http服务,javascript,angularjs,Javascript,Angularjs,我试图通过一个函数(callAPI)调用for循环中的http服务。 这是我的密码。我在这段代码中遇到的问题是,当http服务赶上时,我没有以正确的顺序调用正确的id。在callAPI函数上,它在运行一个http服务异步请求之前,会遍历console.log(id)的所有调用,然后它运行http服务调用,但id的顺序错误。例如,我返回了一个数组[6,6,3],它按[3,6,6]的顺序运行。感谢您的帮助 for (var i = 0; i < idArray.length; i++) {
for (var i = 0; i < idArray.length; i++) {
callAPI(idArray[i]);
}
function getItems() {
return self.choices;
}
function callAPI(id) {
console.log(id);
$http({
method: 'GET',
url: '/api/organizations/' + orgID + '/' + id + '/meal'
}).success(function (data) {
console.log(id);
console.log(data);
// idLocal = id;
angular.forEach(data, function(value,key) {
angular.forEach(value, function(value,key) {
angular.forEach(value, function(value,key) {
if (key == 'description') {
items.push(value);
}
if (key == 'drop_name') {
self.dropName = value;
}
});
});
});
self.choices.push({
id: id,
choice: items,
dropname: self.dropName
});
items = [];
getItems();
}).error(function (data) {
console.log('failed');
});
}
for(变量i=0;i
我更喜欢这样做,但还有多种其他解决方案:
//set index
var index = 0;
function callAPI(id) {
//increment index
index++
$http({
method: 'GET',
url: '/api/organizations/' + orgID + '/' + id + '/meal'
}).success(function (data) {
//call function again with next index if exists
if (index <= idArray.length) {
callAPI(idArray[index])
}
}).error(function (data) {
console.log('failed');
});
}
//call function with 0 index
callApi(idArray[index])
//设置索引
var指数=0;
函数调用API(id){
//增量指数
索引++
$http({
方法:“GET”,
url:'/api/organizations/'+orgID+'/'+id+'/MEIN'
}).成功(功能(数据){
//如果存在下一个索引,请再次调用函数
如果(索引只是因为您按顺序发出请求,并不意味着它们将按顺序返回。如果您确实需要同步运行,则应使用承诺和回调。是的,我将很快阅读承诺。我最近读了很多关于回调的内容。感谢您的输入!可能没有链接直观,但是当然是一种方法。非常感谢您的解决方案。