【问题标题】:How do I execute a function after all resources have resolved?解决所有资源后如何执行功能?
【发布时间】:2013-10-31 20:20:41
【问题描述】:

我如何延迟函数的执行,直到我的所有$resources 都已解决?我的目标是能够解析 log 数组,毕竟 $resources 已解决并将单个成功通知推送到 UI,而不是每次成功推送一个通知。

我的代码基于这个问题angular -- accessing data of multiple http calls - how to resolve the promises。我意识到$scope.promises 是空的,因为item.$save() 没有返回任何内容,但我希望您能看到我正在尝试将未解决的承诺推送到promises 数组。

$scope.save = function () {
  $scope.promises = [];
  $scope.log = [];

  angular.forEach($scope.menuItems, function(item) {
    $scope.promises.push(item.$save(function(menu){
      debugger;                            // execution gets here 2nd
      console.debug("success");
      $scope.log.push(msg: 'success');
    }));
   }, this);

  $q.all($scope.promises).then(function() {
    debugger;                              // execution gets here 1st
    console.debug("all promises resolved");
  });
};

【问题讨论】:

    标签: javascript angularjs q angular-resource


    【解决方案1】:

    由于$save 不返回承诺,您将需要一个中间承诺:

      angular.forEach($scope.menuItems, function(item) {
        var d = $q.defer();   // <--- the intermediate promise
        item.$save(
          function(menu){
            debugger;
            console.debug("success");
            $scope.log.push(msg: 'success');
            d.resolve(menu);  // <--- resolving it, optionally with the value
          },
          function(error){
            d.reject(error);  // <--- rejecting it on error
          }
        );
        $scope.promises.push(d.promise);
       }, this);
    

    顺便说一句,不要忘记扔掉promise数组,否则你会留下垃圾:

    $q.all($scope.promises).then(...).always(function() {
        $scope.promises = null;
    });
    

    并且,如果$scope.promises NOT 暴露给视图,则它不需要在范围内;它可以只是一个 var。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    • 2014-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    相关资源
    最近更新 更多