【问题标题】:Wait for a function to finish multiple resource calls等待一个函数完成多个资源调用
【发布时间】:2017-06-23 07:10:07
【问题描述】:

我是 AngularJS 的新手,在 promise API 上苦苦挣扎。我在控制器中实现了save() 函数,以便获得:

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

RegulationVersionInstallationTypeReg 是针对实体上的每个 http 操作返回 $resource 方法的服务。执行 save() 方法时的问题是我在 Installation type updated 之前获得了 saved! 日志。我想,当我从我的函数中返回 q.all 时,它应该在调用回调之前等待完成所有内部操作。

我做错了什么?

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    似乎有两个问题:1)“saveOperations.push(res);” -- 应该是“saveOperations.push(res.$promise);” -- 在数组中它应该存储承诺而不是整个对象。和 2) saveRegulationInstallationTypes(result).then(console.log('saved!'));应该是 saveRegulationInstallationTypes(result).then(function(){console.log('saved!')});

    【讨论】:

    • 有道理,但即使我将其更改为存储承诺,日志记录顺序仍然保持不变。
    • 尝试以下更改:“saveRegulationInstallationTypes(result).then(console.log('saved!'));”到“saveRegulationInstallationTypes(result).then(function(){console.log('saved!')});”
    • 是的,这与您的回答相得益彰。请编辑并将此评论添加到答案中。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2014-06-21
    • 1970-01-01
    • 1970-01-01
    • 2013-11-23
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    相关资源
    最近更新 更多