如何在 AngularJS 中的 for 循环中调用另一个 HTTP 调用中的一个 HTTP 调用?

How to call one HTTP Call inside another HTTP Call in a for loop in AngularJS?

我正在开发 AngularJS 应用程序。 我有以下数组:

$scope.fruits = [
 {url1: 'appleColor', url2: 'appleDetail'},
 {url1: 'orangeColor', url2: 'orangeDetail'},
 {url1: 'grapesColor', url2: 'grapesDetail'},                 
];

现在,我这样调用 HTTP GET 请求:

for(var i = 0; i < $scope.fruits.length; i++){
   var fruit = $scope.fruits[i];
   getFruitColor(fruit.url1).then(function(color){
      getFruitDetail(fruit.url2).then(function(detail){
         console.log("color is "+ color);
         console.log("detail is "+ detail);
      }):
   });
}

function getFruitColor(url){
   return $http({
        method: 'GET', url: url, params: {} }).then(getFruitComplete, getFruitFailed);
}

function getFruitDetail(url){
    return $http({ method: 'GET', url: url, params: {} }).then(getFruitDataComplete, getFruitDataFailed);
}

function getFruitDataComplete(response) {
    return response.data;
}
        
function getFruitDataFailed(error) {
    $log.error('Failed to get fruit data - '  + error.data);
}
        
function getFruitComplete(response) {
    return response.data;
}
        
function getFruitFailed(error) {
    $log.error('Failed to get fruit- '  + error.data);
}

现在,由于所有这些调用都是异步的,我希望 NETWORK 选项卡中的这些调用是这样的(由于异步性质,这些调用的顺序可能不同):

getFruitColor('appleColor')

getFruitColor('orangeColor')

getFruitColor('grapesColor')

getFruitDetail('appleDetail')

getFruitDetail('orangeDetail')

getFruitDetail('grapesDetail')

但我在“网络”选项卡中实际看到的是:

getFruitColor('appleColor')

getFruitColor('orangeColor')

getFruitColor('grapesColor')

getFruitDetail('grapesDetail')

getFruitDetail('grapesDetail')

getFruitDetail('grapesDetail')

我是 AngularJS 和 Javascript 的初学者,我不明白这里的问题是什么以及为什么在内部 HTTP 调用中,fruits 数组的最后一个元素的 url2 正在进行对于循环中的每个元素。 谁能解释为什么这里会发生这种行为? 我应该怎么做才能达到预期的效果?

尝试使用 let(或 const)代替 var 来完成此作业:var fruit = $scope.fruits[i];。类似的东西应该可以解决问题:

for(var i = 0; i < $scope.fruits.length; i++) {
   const fruit = $scope.fruits[i];
   getFruitColor(fruit.url1).then(function(color) {
      getFruitDetail(fruit.url2).then(function(detail) {

也考虑使用 let i 进行迭代 (for(let i = ...).

请注意,var 将被提升到外部范围,并且每次迭代都会覆盖相同的变量。所有对 getFruitDetail 的调用将仅使用 fruit 的最新值,这就是为什么您会看到 3 个调用 grapesDetail.

varlet/const 之间的主要区别在于 var 是函数作用域,而 let/const 是块范围。这个 link 可能很有趣:https://dev.to/sarah_chima/var-let-and-const--whats-the-difference-69e(或 google 搜索 var/let/const 之间的区别)