0

I know it's sunday evening and most of you will have better thinks to do but a buddy of mine keeps asking me for an application to analyze "the party people" who attend his events...

As part of the application he asked me for some kind of "girls-percentage" calculator for marketing ;)

As Facebook provides access to user data through the Graph API I used this code to retrieve the gender of 1000 users to calculate the percentage.

function getGender(userID) {
    var userGender = "";
    FB.api(
        '/' + userID,
        function (response) {
            if (response && !response.error) {
                userGender = response.gender;
                console.log(userGender);
            }
        }
    );
    return userGender;
}

But the JS function does not return any value, except an empty string... So how do I get JS to assign the value correctly?

Paul S.
  • 64,864
  • 9
  • 122
  • 138
  • try putting var userGender = ""; outside of the first function – user3263978 Jun 01 '14 at 19:45
  • This is easy, if this is how you spend your sundays, the "girls-percentage" will be close or equal to zero, problem solved. – adeneo Jun 01 '14 at 19:46
  • On a more serious note, the facebook API is async, and you can't return from an asynchronous function. – adeneo Jun 01 '14 at 19:46
  • It looks like you're not waiting for your _callback_ but trying to `return` instead; which won't work as the _callback_ hasn't happened yet. – Paul S. Jun 01 '14 at 19:48
  • ^ @adeneo is right. The problem is that the API isn't synchronous. So usergender is still "". You need to use a promise or broadcast a custom event when the call is finished. – Zack Argyle Jun 01 '14 at 19:49
  • It's because asynch callback function is executed after 'return' code. If you share more code, maybe it is easier to help. – Adem İlhan Jun 01 '14 at 19:51

1 Answers1

0

The problem is, that you make call to Facebook API. Your response is asynchronous and don't exist after returning function. The second argument of your function is a callback - your function should do all operations in callback or return promises(in this example, using Q library):

var deferred = Q.defer();

    FB.api('/'+userID, function(response)
    {
     deferred.resolve(response) 
    });

    return deferred.promise;

Good slides about this topic: http://www.slideshare.net/async_io/javascript-promisesq-library-17206726

ArturSkowronski
  • 1,722
  • 13
  • 17
  • Why load library for promises when this particular case can be solved with a simple callback ? – adeneo Jun 01 '14 at 19:59