関数(callAPI)を通じてforループ内でhttpサービスを呼び出そうとしています。 ここに私のコードです。私がこのコードで抱えている問題は、httpサービスがキャッチアップするときに正しいIDで正しいIDを取得できないということです。 callAPI関数では、1つのhttpサービス非同期要求を実行する前にconsole.log(id)のすべての呼び出しを行ってから、httpサービス呼び出しを実行しますが、IDの順序は間違っています。たとえば、 6,6,3]、[3,6,6]の順に実行します。どんな助けもありがとうございます。それが返さ次を実行したときに、ループがHTTPサービスを正しく実行していない
//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])
この1つの非同期リクエストを実行します:
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');
});
}
リクエストを発注しただけで、順番に返されるわけではありません。これを本当に同期的に実行する必要がある場合は、約束とコールバックを使用する必要があります。 – mhodges
はい、私はまもなく約束を読んでいます。私は最近コールバックについてたくさん読んでいます。あなたのご意見ありがとうございます! – wowzuzz