我是AngularJS的一名新手,並且正在努力應對API。我已經實現了一個save()
功能在我的控制器,以獲得:等待一個函數完成多個資源調用
- 的調控版本保存的
- 一旦調控版本保存,其所有安裝類型都保存在一個異步並行方式
- 的
saved!
日誌顯示一切完成後,(在我的實際應用中我想去這裏其他應用程序的狀態)
這就是我目前在我的控制器代碼:
var saveRegulationInstallationTypes = function (result) {
var saveOperations = [];
angular.forEach(vm.installationTypeRegs, function (
installationTypeReg, key) {
installationTypeReg.regulationVersion = result;
var res = InstallationTypeReg.update(installationTypeReg, function() {
console.log('Installation type updated');
});
saveOperations.push(res);
});
return $q.all(saveOperations);
}
function save() {
var regulationVersionSaved = RegulationVersion.update(vm.regulationVersion);
return regulationVersionSaved.$promise.then(
function (result) {
saveRegulationInstallationTypes(result).then(console.log('saved!'));
});
}
RegulationVersion
和InstallationTypeReg
在返回$resource
方法在每個實體的HTTP業務的服務。執行save()方法時的問題是,我在Installation type updated
之前得到了saved!
日誌。我想,當我從函數返回q.all
時,它應該等待在調用回調之前完成所有內部操作。
我在做什麼錯?
它是有道理的,但即使我改變它來存儲承諾,日誌記錄順序保持不變。 –
嘗試使用以下更改: 「saveRegulationInstallationTypes(result).then(console.log('saved!'));」 到 「saveRegulationInstallationTypes(result).then(function(){console.log('saved!')});」 –
是的,這與你的答案使竅門。請編輯並將此評論添加到答案中。謝謝! –