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;
      });
  }
});
4
  • Object is just another Class called Study that contains inside it a list of cases, each of these cases has a list of steps. So I need to be able to index inside of the callback function. Commented Jul 25, 2014 at 19:37
  • 1
    where do you get i from? Commented Jul 25, 2014 at 19:40
  • Please see the code I just added in my question. Commented Jul 25, 2014 at 19:47
  • possible duplicate of Can promises have multiple arguments to onFulfilled? Commented Jul 26, 2014 at 7:51

2 Answers 2

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);
   }
});
Sign up to request clarification or add additional context in comments.

1 Comment

This answer elaborates a bit on defining a function that returns a callback that can use additional data.
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]);
});

1 Comment

This doesn't give the opportunity to pass the key through to the .then() function. You have just hardcoded the keys in the JS

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.