javascript - 等待函数完成多个资源调用

标签 javascript angularjs

我是 AngularJS 的新手,正在为 Promise API 苦苦挣扎。我在 Controller 中实现了 save() 函数以获得:

  1. 已保存法规版本
  2. 规则版本保存后,其所有安装类型都会以异步并行的方式保存
  3. 一切完成后显示的 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!'));
    });
}

RegulationVersionInstallationTypeReg 是为实体上的每个 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/

相关文章:

javascript - 如何在angularjs中使用带有嵌套ng-repeat的复选框

javascript - 选择框中的 ng-model 无法正常工作

javascript - 如何修复使用从另一个文件导入的函数时出现的 'Unexpected identifier' 错误

javascript - 从符号/它的字形中删除/忽略空白或墨迹

javascript - Intellij 应该在 Typescript 文件中使用单括号

javascript - 如何创建现有指令的专门版本?

javascript - 对 null 或空值使用 ng-switch

javascript - 做改变并保存 Jquery PHP

javascript - 在 Android 上处理 webkit.messageHandler postMessage

html - 下拉菜单在 Windows Chrome 中切断字母