[英]Using closure with a promise in AngularJS
我沒有JavaScript closures
的經驗,也沒有AngularJS promises
的經驗。 所以,這是我的情況
目標 :
我需要在for
循環中進行$http
請求調用
(顯而易見的)問題
即使循環已完成,我的變量仍未更新
當前實施
function getColumns(fieldParameters)
{
return $http.get("api/fields", { params: fieldParameters });
}
for(var i = 0; i < $scope.model.Fields.length; i++)
{
var current = $scope.model.Fields[i];
(function(current){
fieldParameters.uid = $scope.model.Uid;
fieldParameters.type = "Columns";
fieldParameters.tableId = current.Value.Uid;
var promise = getColumns(fieldParameters);
promise.then(function(response){
current.Value.Columns = response.data;
}, error);
})(current);
}
//at this point current.Value.Columns should be filled with the response. However
//it's still empty
我該怎么做?
謝謝
var promises = [];
for(var i = 0; i < $scope.model.Fields.length; i++)
{
var current = $scope.model.Fields[i];
promises.push(function(current){
//blahblah
return promise
});
}
$q.all(promises).then(function(){
/// everything has finished all variables updated
});
如果我正確理解了您的問題,那么您會得到一些需要做的工作的字段列表。 然后,當所有異步工作完成后,您想要繼續。 因此,使用$ q.all()應該可以解決問題。 當所有交給它的承諾清單都解決時,它將解決。 因此,這本質上就像是“等所有這些東西都完成后再執行此操作”
您可以嘗試這樣的事情:
var promises = [];
for(var i=0; i< $scope.model.Fields.length; i++) {
var current = $scope.model.Fields[i];
promises.push(getColumns(fieldParameters).then(function(response) {
current.Value.Columns = response.data;
}));
}
return $q.all(promises).then(function() {
// This is when all of your promises are completed.
// So check your $scope.model.Fields here.
});
編輯:
嘗試此操作,因為您沒有看到正確的項目更新。 更新您的getColumns方法以接受該字段,然后在getColumns調用中發送該字段:
function getColumns(fieldParameters, field)
{
return $http.get("api/fields", { params: fieldParameters}).then(function(response) {
field.Value.Columns = response.data;
});
}
...
promises.push(getColumns(fieldParameters, $scope.model.Fields[i])...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.