javascript 在angularjs中将参数传递给promise的回调

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24963151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 03:40:18  来源:igfitidea点击:

Passing parameters to promise's callback in angularjs

javascriptangularjspromisecallback

提问by user3799365

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.

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

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

回答by Yaron Schwimmer

you can use a closurefor 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);
   }
});

回答by Dylan

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()在一系列的承诺上,比如:

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