簡體   English   中英

無法循環訪問API響應/訪問循環變量

[英]Unable to loop through API response / access loop variables

我正在嘗試構建一個簡單的Twitter feed應用程序,但是在實現刷新功能方面遇到困難。

    $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(function(data)中的x(全局變量,在其他任何地方未使用)的值似乎與循環中的其他任何地方都不相同,並且似乎沒有增加,我嘗試使用$ scope。如果我將其硬編碼為僅刷新tweetsarray中的[0],但是[x]返回一個單獨的值,則刷新有效。

2)我想嘗試通過遞延的Promise循環功能存在某種問題。 有沒有一種方法可以確保我在每次循環中都保證在繼續之前返回了諾言?

謝謝,謝謝您的幫助!

-戴夫

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

這意味着將數組元素傳遞給異步任務,然后返回響應,然后使用它找到數組索引並更新元素

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM