【问题标题】:Passing parameters to promise's callback in angularjs在angularjs中将参数传递给promise的回调
【发布时间】:2014-09-17 17:54:38
【问题描述】:

我试图弄清楚是否有任何方法可以将索引参数传递给 Promise 的回调函数。例如。

serviceCall.$promise.then(function(object){
    $scope.object = object;
});

现在我想传入一个数组索引参数为

serviceCall.$promise.then(function(object,i){
    $scope.object[i] = something;
});

这可以吗?请告诉我。

下面是代码

StudyService.studies.get({id:    
$routeParams.studyIdentifier}).$promise.then(function(study) {
$scope.study = study;
for(var i=0;i<study.cases.length;i++){
  StudyService.executionsteps.get({id:   
  $routeParams.studyIdentifier,caseId:study.cases[i].id})
      .$promise.then(function(executionSteps,i){
      $scope.study.cases[i].executionSteps = executionSteps;
      });
  }
});

【问题讨论】:

  • Object 只是另一个名为 Study 的类,其中包含一个案例列表,每个案例都有一个步骤列表。所以我需要能够在回调函数内部建立索引。
  • 你从哪里得到i
  • 请看我刚刚在我的问题中添加的代码。

标签: javascript angularjs promise callback


【解决方案1】:

我做了类似的事情,我对每个人都做了一个承诺,然后在一系列承诺上使用了$q.all(),例如:

$q.all( arrayOfPromises )
.then(function(results) {
   console.log(results[0], results[1], results[2]);
});

【讨论】:

  • 这没有机会将密钥传递给 .then() 函数。您刚刚对 JS 中的键进行了硬编码
【解决方案2】:

您可以为此使用closure

例如,在您的代码中,使用如下内容:

function callbackCreator(i) {
  return function(executionSteps) {
    $scope.study.cases[i].executionSteps = executionSteps;
  }
}
StudyService.studies.get({id: $routeParams.studyIdentifier})
  .$promise.then(function(study) {
    $scope.study = study;
    for(var i=0;i<study.cases.length;i++) {
      var callback = callbackCreator(i);
      StudyService.executionsteps.get({id: $routeParams.studyIdentifier,caseId:study.cases[i].id})
        .$promise.then(callback);
   }
});

【讨论】:

  • This answer 详细说明了定义一个返回可以使用附加数据的回调的函数。
猜你喜欢
  • 2015-12-04
  • 2015-12-06
  • 2016-11-18
  • 2014-03-25
  • 2016-12-09
  • 2018-04-29
  • 2015-08-31
  • 1970-01-01
相关资源
最近更新 更多