DaveS
DaveS

Reputation: 99

For Loops & Promises

I'm having some trouble managing a for loop with multiple promises. I've read that I should use $q.all, but I havent had any success with it thus far. I need this function to make sure all of the async calls inside the for loop have occurred.

refreshFeed: function(){    
    var defer = $q.defer();
    var promises = []; // array of promises

    for (var x = 0; x < userdata.length; x++){
        this.getLatest(x).then(function(){
            promises.push(x);
        });    
    }
    console.log(userdata); // this is updated successfully by getLatest(x)

    $q.all(promises).then(function(){ 
        defer.resolve();
    })

    return defer; 
}

It successfully prints the console.log but then I get the console error "undefined is not a function" at the line that initially calls refreshFeed().

Any help would be appreciated. Thank you!

Edit:

getLatest: function(x){ 
            var deferred = $q.defer();
            var promise = twitterService.getLatestTweets(userdata[x].searchterm, userdata[x].sources).then(function(data) {
                userdata[x].tweets = data;
                console.log(userdata[x].tweets);
                deferred.resolve();
            });
            return deferred.promise;
    }

Update: I used PSL's answer and toyed around with getLatest and I finally got it to work. I just needed to replace the userdata[x]'s with the function parameter. Thanks @PSL

Upvotes: 2

Views: 106

Answers (1)

PSL
PSL

Reputation: 123739

You would need to pass an array of promises and even if you are using deferred pattern you are not resolving anything. Assuming getLatest returns a promise you could just do:-

refreshFeed: function(){    
    return $q.all(userdata.map(this.getLatest));
}

Array.map

Upvotes: 2

Related Questions