-1

i have this block of code:

$(document).ready(function() {
    //<![CDATA[  
    var who;

    FB_RequireFeatures(["Api"], function(){ 

        var who = api.get_session().uid;
        alert(who);

        });

        alert("the uid is: "+who);

    //]]> 
});

the problem: the code outside the FB_RequireFeatures block is executing before the one inside it. due to which the value of who is coming out to be undefined.

what am i doing wrong?

1
  • This question is similar to: How do I return the response from an asynchronous call?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Dec 1, 2024 at 14:32

2 Answers 2

3

The FB_RequireFeatures function appears to be making an asynchronous call, so you're not doing anything wrong, that's just the way it works - the alert is called before the request comes back.

You must design your code in a way that the code that depends on the result of the FB_RequireFeatures functions are called only after the request completes. You can call another function inside the callback, for example:

var who;

$(document).ready(function() {        
    FB_RequireFeatures(["Api"], function() {
        who = api.get_session().uid;
        doSomeOtherStuff();
    });
});

function doSomeOtherStuff() {
    alert("the uid is: " + who);
}

Now the doSomeOtherStuff function is called only after the FB_RequireFeatures function finishes, and you should do all following code inside the doSomeOtherStuff function – which you can name to be anything you want, obviously.

I moved the who variable out of the ready block to keep it in scope for the doSomeOtherStuff function, and removed the var from the inner function so that you're referencing the original variable instead of creating a new one, otherwise it's the same.

Sign up to request clarification or add additional context in comments.

4 Comments

how to make sure the code that follows the function gets executed after FB_RequireFeatures is done requesting?
that does help things a bit. but can something be done to make the code after the FB_RequireFeatures to wait explicitly for FB_requireFeatures to finish?
i tried the above method. for some reason the code in someotherfunction() is still getting executed before the ajax call completes?
@amit: no, you can't turn asynchronous execution code into synchronous or vice-versa. All code you want to run when FB_RequiresFeatures has finished must be passed to it as a callback function.
2

You're making a new local who variable. Remove the var from the place where you set who. Also, you can't reference who until the callback to the FB_RequireFeatures function is run.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.