如果我正確理解你的問題。您希望以同步方式運行for循環,以便只有在前一次迭代完成後纔會發生下一次迭代。爲此,您可以使用同步循環/回調。特別是如果訂單很重要。
var syncLoop = function (iterations, process, exit) {
var index = 0,
done = false,
shouldExit = false;
var loop = {
next: function() {
if (done) {
if (shouldExit && exit) {
return exit(); // Exit if we're done
}
}
// If we're not finished
if (index < iterations) {
index++; // Increment our index
process(loop); // Run our process, pass in the loop
// Otherwise we're done
} else {
done = true; // Make sure we say we're done
if (exit) exit(); // Call the callback on exit
}
},
iteration: function() {
return index - 1; // Return the loop number we're on
},
break: function (end) {
done = true; // End the loop
shouldExit = end; // Passing end as true means we still call the exit callback
}
};
console.log('running first time');
loop.next();
return loop;
}
爲了您的具體實現:
syncLoop(myArray.length, function (loop) {
var index = loop.iteration();
var data = {
"myQuery": myArray[index].query
};
$http.post("/myServiceUrl", data).success(function (result) {
console.log(result);
loop.next();
});
}, function() {
console.log('done');
});
如果你打算做一些與數據一次返回(如執行計算),你可以用這個方法做,因爲你將返回的數據一個特定的順序。
我在我構建的統計計算web應用程序中實現了類似的東西。
編輯:
爲了說明我使用的時候$ q.when我已成立了一個小提琴有問題。希望這將有助於說明我爲什麼按照我的方式做到了這一點。
https://jsfiddle.net/chrislewispac/6atp3w8o/
從馬特的答案使用下面的代碼:
var chain = $q.when(promise.getResult());
angular.forEach(myArr, function (item) {
chain = chain.then(function() {
$rootScope.status = item;
console.log(item);
});
});
// the final chain object will resolve once all the posts have completed.
chain.then(function() {
console.log('all done!');
});
這琴是我的解決方案的一個例子:
https://jsfiddle.net/chrislewispac/Lgwteone/3/
的$ Q版進行比較,以我的版。查看控制檯並想象那些交付給用戶界面的用戶在過程中進行用戶干預和/或對順序退貨執行統計操作。
你會發現它不會在控制檯或Matt的回答中的視圖中依次給出數字1,2,3,4等。它'批'的反應,然後返回它們。因此,如果根據步驟2中的響應不執行步驟3,則至少在提供的答案中不存在突破或顯式控制此處的同步操作的方式。這在嘗試執行順序計算和/或允許用戶控制斷點等時提出了重大問題。
現在,我正在挖掘$ q庫和Q庫以查看是否有更多這個問題的優雅解決方案。但是,我的解決方案按照要求工作,並且非常明確,它允許我將該函數放置在服務中,並按照我的意願操作某些用例,因爲我完全理解它在做什麼。對我而言,這比使用庫更重要(至少在我作爲程序員開發的這個階段,我確信在StackOverflow的同一階段還有很多其他人)。
命令是否重要? – Teliren
你可以在瀏覽器中使用'async'軟件包,使用'$ http'。唯一的問題是如果你想用你的結果更新'$ scope',那麼你可能需要使用'$ scope。$ apply'或'$ timeout'(沒有可選的延遲) – Jack