0

I am new to facebook apps.I am using javascript sdk.Any one can help me pls for fallowing problem I calculating number likes of album photos: This is my code

FB.api('/'+album.id+'/photos', function(photos){

            if (photos && photos.data && photos.data.length){
             for (var j=0; j<photos.data.length; j++){                              
                var photo = photos.data[j];
                var id=photo.id;
                var likescount=0;

              jQuery.getJSON('https://graph.facebook.com/'+id+"/likes/?access_token="+accessToken,function(data)
                            {                           
                        likescount=data.data.length;
                        console.log("likes count : "+likescount);
                        });
                    console.log("no of likes :"+likescount);

              }                 //end of iterate photos  for loop
            }           //end of photo exist if block  
          });

According to my code its o/p will be likes count : 2 no of likes : 2 likes count : 3 no of likes : 3 likes count : 0 no of likes : 0 likes count : 2 no of likes : 2

But it return the result as no of likes : 0 no of likes : 0 no of likes : 0 no of likes : 0

likes count : 2 likes count : 3 likes count : 0 likes count : 2

  • The getJSON calls are asynchronous - the callback function you passed could happen at any time depending on how quickly the Facebook API returns the result. The code doesn't wait for the API call to finish before continuing. – madebydavid Jan 16 '14 at 14:18

1 Answers1

0

Mostly Javascript is asynchronous. "asynchronous" meaning that the operation occurs in parallel and the order of completion is not guaranteed.

In your case jQuery.getJSON() is asynchronous. To make it synchronous try to make request as below

$.ajax({  url: 'https://graph.facebook.com/'+id+"/likes/?access_token="+accessToken,  dataType: 'json',  async: false,  success: function(data) {       //stuff  }});

ref : Is it possible to set async:false to $.getJSON call

Community
  • 1
  • 1
SRT
  • 1
  • 2