16

I am trying to figure out is there is any way to pass in an index argument to a promise's callback function. For instance.

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

Now I want to pass in an array index parameter as

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

Can this be done? Please let me know.

Here is the code below

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;
      });
  }
});
Yaron Schwimmer
  • 5,327
  • 5
  • 36
  • 59
user3799365
  • 1,087
  • 4
  • 17
  • 27

2 Answers2

21

you can use a closure for that.

for example, in your code, use something like:

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);
   }
});
sfletche
  • 47,248
  • 30
  • 103
  • 119
Yaron Schwimmer
  • 5,327
  • 5
  • 36
  • 59
  • [This answer](http://stackoverflow.com/a/939206/187812) elaborates a bit on defining a function that returns a callback that can use additional data. – Josh Diehl Nov 10 '14 at 22:36
0

I've done something similar and I put a promise on each and then used $q.all() on the array of promises like:

$q.all( arrayOfPromises )
.then(function(results) {
   console.log(results[0], results[1], results[2]);
});
Dylan
  • 4,703
  • 1
  • 20
  • 23
  • 1
    This doesn't give the opportunity to pass the key through to the .then() function. You have just hardcoded the keys in the JS – SM3RKY Dec 09 '15 at 20:51