在AngularJS中传递参数给Promise的回调函数

16

我正在尝试弄清楚是否有办法向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;
      });
  }
});

对象只是另一个名为Study的类,其中包含一系列案例,每个案例都有一系列步骤。因此,我需要能够在回调函数内进行索引。 - user3799365
1
你从哪里得到 i 的值? - Yaron Schwimmer
请查看我刚刚在问题中添加的代码。 - user3799365
可能是重复的问题:Promises 的 onFulfilled 回调函数可以有多个参数吗? - Benjamin Gruenbaum
2个回答

21

你可以使用闭包来实现这个功能。

举个例子,在你的代码中,可以像这样使用:

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);
   }
});

这个答案详细阐述了如何定义一个返回回调函数并能使用额外数据的函数。 - Josh Diehl

0

我之前做过类似的事情,我在每个上放了一个 Promise,然后在 Promise 数组上使用 $q.all() 方法:

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

1
这样做不会给通过.then()函数传递密钥的机会。您只是在JS中硬编码了密钥。 - SM3RKY

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接