我是 AngularJS 的新手,正在为 Promise API 苦苦挣扎。我在 Controller 中实现了 save()
函数以获得:
- 已保存法规版本
- 规则版本保存后,其所有安装类型都会以异步并行的方式保存
- 一切完成后显示的
saved!
日志(在我的真实应用程序中,我想在此处转到其他应用程序状态)
这是我 Controller 中当前的代码:
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
是为实体上的每个 http 操作返回 $resource
方法的服务。执行 save() 方法时的问题是,我在 Installation type Updated
日志之前收到 saved!
日志。我想,当我从函数返回 q.all
时,它应该等待完成所有内部操作,然后再调用回调。
我做错了什么?
最佳答案
似乎有两个问题:1)“saveOperations.push(res);” -- 应该是“saveOperations.push(res.$promise);” -- 正如在数组中一样,它应该存储 promise 而不是整个对象。 2) saveRegulationInstallationTypes(result).then(console.log('已保存!'));应该是 saveRegulationInstallationTypes(result).then(function(){console.log('saved!')});
关于javascript - 等待函数完成多个资源调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44715214/