无法循环通过API响应/访问循环变量

Unable to loop through API response / access loop variables

本文关键字:循环 访问 响应 变量 API      更新时间:2023-09-26

我正在尝试构建一个简单的Twitter提要应用程序,但在实现刷新功能时遇到了困难。

    $scope.refreshTimeline = function() {
  for (x = 0; x < $scope.tweetsarray.length; x++){ // loop through the twitter feeds
    twitterService.getLatestTweets($scope.tweetsarray[x].name).then(function(data) {
      $scope.tweetsarray[x].tweets = data; //update each
    });
  }
}

以及getlatesttweets函数

getLatestTweets: function (name) {
        //create a deferred object using Angular's $q service
        var deferred = $q.defer();
        var promise = authorizationResult.get('https://api.twitter.com/1.1/search/tweets.json?q='+name+'&count=8').done(function(data) {
            //when the data is retrieved resolved the deferred object
            deferred.resolve(data)
        });
        //return the promise of the deferred object
        return deferred.promise;
    }

以下是我使用的问题

1) .then(函数(数据)中的x(全局变量,在其他任何地方都未使用)的值似乎与循环中的其他任何地方不同,而且似乎没有增加。我试过在循环中使用$scope.x或将其作为函数变量。如果我将其硬编码为只刷新tweetarray中的[0],则刷新有效,但[x]返回一个单独的值。

2) 我猜,试图循环通过一个具有延迟承诺的函数会有某种问题。有没有一种方法可以确保在每次通过循环时,在继续之前都会返回promise?

谢谢你的帮助!

-Dave

由于javascript的关闭行为,它将在从服务回调时获取最新的x值。所以试着用这种方式。

 $scope.refreshTimeline = function() {
  for (var x = 0; x < $scope.tweetsarray.length; x++){ 
    storeTweets(x);       
  }
 }
 function storeTweets(x){
    twitterService.getLatestTweets($scope.tweetsarray[x].name).then(function(data) {
      $scope.tweetsarray[x].tweets = data; //update each
    });
 }

您可以执行类似的操作

 $scope.refreshTimeline = function() {
   for (x = 0; x < $scope.tweetsarray.length; x++){ // loop through the twitter feeds
      var data;
      data.tweet = $scope.tweetsarray[x];
      twitterService.getLatestTweets($scope.tweetsarray[x].name).then(function(data) {
      $scope.tweetsarray[$scope.tweetsarray.indexof(data.tweet)].tweets = data; //update each
    });
   }
 }

这意味着,将数组元素传递给异步任务,它会返回到响应中,然后使用它来查找数组索引并更新元素