Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have the foreach loop to wait for $http.get to complete before moving on?

I cannot seem to have the code to pause and wait for the $http response before moving on. Currently my code looks something like this:

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

But when it ran, the console.log output is not what i had expected.

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

The output that I was expecting is having the console.log(JSON.stringify(postAuthorCache)); to run at the beginning, then after querying $http, it runs either console.log("NOT CACHE: " + value["post_author"]); or console.log("IN CACHE: " + value["post_author"]);. Afterwords, it should repeat itself by displaying the stringify for the array object again, and proceed with the NOT CACHE or IN CACHE log statements.

So the question is, how would the foreach loop to wait for $http.get to complete, before moving on?

like image 213
EndenDragon Avatar asked Dec 13 '25 21:12

EndenDragon


1 Answers

You need to cache the fact that you're about to do a query, eg:

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

You'll probably want to add some extra error checking though. Also note that it's possible to get the responses directly in the latter handler without going via postResponseCache, but this is easier.

like image 109
Miral Avatar answered Dec 15 '25 10:12

Miral



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!