我是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!')});” –
是的,这与你的答案使窍门。请编辑并将此评论添加到答案中。谢谢! –