0

I have this basic for loop that iterates through a user's followers. I want to console.log the list of followers from outside of this function as I want to compare this array to another another array somewhere else. How do I do this?

    // Run through user's followers
    SC.get('/users/9110252/followings',function(followings) {

    var userFollowings = [];


        for(i = 0; i < followings.collection.length; i++) {         

            userFollowings.push(followings.collection[i].username);           

        }   

    });

    console.log(userFollowings);
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
mellows
  • 303
  • 1
  • 7
  • 27
  • You could return userFollowing from the function. Or you could just log it within the function, what's wrong with doing that? – Mark Chorley May 06 '16 at 11:10

4 Answers4

1

I guess your SC.get method is asynchronous, and that's why you can't return userfollowings from it.

However, you can put the declaration outside. This won't be enough as the console.log would be evaluated before the end of SC.get. Usually, dealing with asynchronous functions involves promises or callbacks. :

    var userFollowings = [];
        SC.get('/users/9110252/followings').then(function(followings) {
            for(i = 0; i < followings.collection.length; i++) {  
userFollowings.push(followings.collection[i].username); 
            }   

        }).done(function() {
        console.log(userFollowings);
    });

That way, console.log will be evaluated with the right userFollowings array

Community
  • 1
  • 1
Regis Portalez
  • 4,675
  • 1
  • 29
  • 41
0

Define the array outside of the function. It can use it thanks to Closure.

var userFollowings = [];

// Run through user's followers
SC.get('/users/9110252/followings',function(followings) {
    for(i = 0; i < followings.collection.length; i++) {         
       userFollowings.push(followings.collection[i].username);           
    }   
});

console.log(userFollowings);
Radek Pech
  • 3,032
  • 1
  • 24
  • 29
0

Declare var userFollowings = []; outside the function.

var userFollowings = [];
// Run through user's followers
SC.get('/users/9110252/followings',function(followings) 


    for(i = 0; i < followings.collection.length; i++) {         

        userFollowings.push(followings.collection[i].username);           

    }   

});

console.log(userFollowings);
Munawir
  • 3,346
  • 9
  • 33
  • 51
0

You can just wrap your code into immediately invoked function and return the needed array:

var userFollowings = function(){ 
    var len = followings.collection.length, userFls = [];
    SC.get('/users/9110252/followings',function(followings) {          
        while (len--) {
            userFls.push(followings.collection[len].username);
        }
    });

    return userFls;
}();

console.log(userFollowings);
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105