2016-05-04 196 views
3

在繼續之前,我似乎無法讓代碼暫停並等待$ http響應。目前我的代碼看起來像這樣:

var postAuthorCache = new Array(); 
angular.forEach($scope.news.posts, function(value, key) { 
    console.log(JSON.stringify(postAuthorCache)); //Keeps printing "[]" 
    if (!(value["post_author"] in postAuthorCache)) { 
     $http.get('/api/tumblr_primaryblog_name/' + value["post_author"]).then(function(response) { 
      postAuthorCache[value["post_author"]] = response.data; 
      value["post_author_pblog"] = postAuthorCache[value["post_author"]]; 
      console.log("NOT CACHE: " + value["post_author"]); 
     }); 
    } else { 
     value["post_author_pblog"] = postAuthorCache[value["post_author"]]; 
     console.log("IN CACHE: " + value["post_author"]); 
    }; 
}); 

但是當它運行時,console.log輸出不是我所期望的。

[] 
[] 
[] 
[] 
[] 
[] 
[] 
NOT CACHE: aaaa 
NOT CACHE: bbbb 
NOT CACHE: aaaa 
NOT CACHE: aaaa 
NOT CACHE: aaaa 
NOT CACHE: aaaa 
NOT CACHE: bbbb 

,我期待是具有console.log(JSON.stringify(postAuthorCache));在開始時運行,然後查詢$ HTTP後的輸出,它運行要麼console.log("NOT CACHE: " + value["post_author"]);console.log("IN CACHE: " + value["post_author"]);。後綴,它應該通過再次顯示數組對象的字符串化來重複,並繼續執行NOT CACHEIN CACHE日誌語句。

所以問題是,在繼續之前,foreach循環如何等待$ http.get來完成?

+0

多種方式來達到這個目的,但更好地理解你將如何實際使用這些值,因爲'console.log'消息順序可能不是你想要如何使用它?如果是這樣,你可以手動循環訪問數組,而不是使用'forEach',並且保持當前'index'的運行計數?並且只能在'.get'回調中計算'index' – Akurn

+0

[有沒有在angular.foreach中實現Promise的可能方法?](http://stackoverflow.com/questions/36997004/is-there-a -possible-way-implemented-promise-inside-angular-foreach) – Maverick

回答

0

試試這個代碼 -

var deferred = $q.defer(); 
    $http.post('/api/tumblr_primaryblog_name/' + value["post_author"]).then(
     function successCallback(response){ 
      deferred.resolve(response); 
      return deferred.promise; 
     }, 
     function errorCallback(response){ 
      deferred.reject(response); 
      return deferred.promise; 
     }); 
+0

@downvoter:爲什麼? – naveen

+0

我沒有downvote,但這實際上並不回答問題的任何部分。這也是多餘的,因爲'$ http.post'已經返回一個承諾。 – Miral

0

的一種方法是使用遞歸等待每個調用完成來實現。檢查here

另一種方法是使用承諾鏈接here

+1

這應該是評論,而不是答案。 – naveen

1

需要緩存的事實,你將做一個查詢,如:

var postRequestCache = {}; 
var postResponseCache = {}; 
angular.forEach($scope.news.posts, function(value, key) { 
    var author = value["post_author"]; 
    if (!(author in postRequestCache)) { 
     postRequestCache[author] = $http.get('/api/tumblr_primaryblog_name/' + author).then(function(response) { 
      postResponseCache[author] = response.data; 
     }); 
    } 
}); 
$q.all(postRequestCache).then(function() { 
    angular.forEach($scope.news.posts, function (value, key) { 
     var response = postResponseCache[value["post_author"]]; 
     value["post_author_pblog"] = response.response.blog.title; 
    }); 
}); 

您可能需要添加一些額外的錯誤檢查雖然。另外請注意,可以不通過postResponseCache直接在後者中獲得響應,但這更容易。

相關問題