NebraskaJS Message Board › async Facebook JS (and jQuery) call issues

async Facebook JS (and jQuery) call issues

A former member
Post #: 5
A plea for help from all of the JS wizards here...

I am trying to query the FB api using their SDK, and save the value, so I can compute with another value I am getting later, with another API call.

But since everything is asychronous, I am lost. Nothing seems to work. I think the solution involves "context" somehow, but I am out of my element. Here is the simplified code that giving me problems:

<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'your app id', status: true, cookie: true,
xfbml: true});

// pageQueries is an collection of FQL query strings to run, it's set up elsewhere
var exampleVar = 0;
for(var j in pageQueries) {

var fans; // I want to save fans here

// get fan count as of day today
FB.api(
{ method: 'fql.query',
query: pageQueries[j].myQuery },
function(response) {
fans = response; // this is the value I want to save
}
);

console.log(fans); // but it's undefined here, because the async FB.api method has not run yet.
console.log(exampleVar); // this echoes 0, 1, etc as expected

// get fan count a month ago
FB.api(
{ method: 'fql.query',
query: pageQueries[j].myOtherQuery },
function(response) {
//newFans = fans - response; // this is basically what I want to do
console.log(fans); // // "fans" is usually undefined - but it has values sometimes, if one of the queryies above has completed
console.log(exampleVar); // this is always 2 (or whatever the loop count is),
// since the loop is already complete before this echos - another example of async weirdness
}
);

exampleVar++;
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appen­dChild(e);
}());
</script>

Man... the no code formatting options in this forum? Bummer...

Anyway, if anyone takes a look I'd love some suggestions about how to solve this.

Thank you!!!
Powered by mvnForum

People in this
Meetup are also in:

Sign up

Meetup members, Log in

By clicking "Sign up" or "Sign up using Facebook", you confirm that you accept our Terms of Service & Privacy Policy