【问题标题】:Using closure with a promise in AngularJS在 AngularJS 中使用带有 Promise 的闭包
【发布时间】:2016-12-12 01:39:55
【问题描述】:

我对@9​​87654321@ 和AngularJS promises 没有太多经验。所以,这是我的场景

目标

我需要在for 循环中调用$http 请求

(明显)问题

即使循环完成,我的变量仍然没有更新

当前实施

function getColumns(fieldParameters)
{
    return $http.get("api/fields", { params: fieldParameters });
}

for(var i = 0; i < $scope.model.Fields.length; i++)
{
    var current = $scope.model.Fields[i];

    (function(current){
        fieldParameters.uid = $scope.model.Uid;
        fieldParameters.type = "Columns";
        fieldParameters.tableId = current.Value.Uid;                    
        var promise = getColumns(fieldParameters);                  
        promise.then(function(response){
           current.Value.Columns = response.data;
        }, error); 
    })(current);                                                                     
}

//at this point current.Value.Columns should be filled with the response. However
//it's still empty

我能做些什么来实现这个目标?

谢谢

【问题讨论】:

    标签: javascript angularjs closures angular-promise


    【解决方案1】:

    如果我正确理解了您的问题,那么您有一个需要处理的字段列表。然后,当所有异步工作完成后,您想继续。所以使用 $q.all() 应该可以解决问题。当交给它的所有承诺列表都解决时,它将解决。所以它本质上就像“等到所有这些东西都完成,然后再做”

    你可以试试这样的:

    var promises = [];
    
    for(var i=0; i< $scope.model.Fields.length; i++) {
      var current = $scope.model.Fields[i];
      promises.push(getColumns(fieldParameters).then(function(response) {
        current.Value.Columns = response.data;
      }));
    }
    
    return $q.all(promises).then(function() {
      // This is when all of your promises are completed.
      // So check your $scope.model.Fields here. 
    });
    

    编辑:

    试试这个,因为您没有看到正确的项目更新。更新您的 getColumns 方法以接受该字段,在 getColumns 调用中发送该字段:

    function getColumns(fieldParameters, field)
    {
        return $http.get("api/fields", { params: fieldParameters}).then(function(response) {
    field.Value.Columns = response.data;
        });
    }
    
    
    ...
    
    promises.push(getColumns(fieldParameters, $scope.model.Fields[i])...
    

    【讨论】:

    • 它可以工作,但是数据没有更新到正确的current对象。这就是为什么我认为我需要在这里关闭。无论如何,我都会为你的部分答案投票。
    • @LuisLavieri 查看我上面的编辑。我认为这应该可以解决问题。
    • 谢谢。那非常接近。我必须通过该死的i 并在$http 中填充fieldParameter 对象以使其最终工作
    • @LuisLavieri 重要的是你相信自己。永不放弃。 ;)
    【解决方案2】:
      var promises = [];      
    
      for(var i = 0; i < $scope.model.Fields.length; i++)
      {
         var current = $scope.model.Fields[i];
         promises.push(function(current){
             //blahblah 
             return promise
         });
      }
    
    
      $q.all(promises).then(function(){
          /// everything has finished all variables updated
      });
    

    【讨论】:

    • 它可以工作,但是数据没有更新到正确的current对象。这就是为什么我认为我需要在这里关闭。但是,我仍然会支持您的部分答案。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    • 1970-01-01
    • 1970-01-01
    • 2012-06-17
    • 1970-01-01
    • 2018-06-16
    • 1970-01-01
    相关资源
    最近更新 更多