0

I am setting up a Google+ sign in, and I'm trying to set the email to a variable outside of the function that actually gets the email so that I can use it later for account creation. However I am having issues with scope in Javascript. When I run this code (note this is only part of the code), the first alert box that I get says "2: asdf" and the second alert box that I get says "1: [insert email here]". What I am expecting to get is to have the alert("2: " + email); have the email in it, instead of asdf, but it's not doing that. Any ideas?

    var email = "asdf";
    // Get the email
    gapi.client.load('oauth2', 'v2', function()
    {
        gapi.client.oauth2.userinfo.get().execute(function(resp) {
            email = resp.email;
            alert("1: " + email);
        });
    });

    alert("2: " + email);
JYeh
  • 4,273
  • 3
  • 27
  • 40
  • 1
    The alert(2) is running immediately, before the response is received. If you want it to wait for the response, put it inside the callback right after the alert(1). – Raymond Chen Nov 10 '13 at 00:09

1 Answers1

0

That's not a scope issue, that is a time issue.

The execute method is asynchronous, so the callback function that you give to it will not be executed immediately. It will hang on to the function, and call it once the answer arrives.

The code after the call will continue before the answer arrives, so the second alert will run before the email variable is changed. Then your code block ends and control is returned to the browser. Before you have returned the control to the browser, it can't handle the event that is triggered when the answer arrives, which means that the first alert can never come before the second alert.

If you want to use the value from the answer, you have to do it inside the callback function. As the execute method is asynchronous, you have to write your code to handle the answer asynchronously also.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • How might I modify my code to use a deferred object instead? I looked at http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call and it seems to describe my problem and the top answer says the best option is to use a deferred object, but the format of their example isn't very similar to what I have. – JYeh Nov 10 '13 at 00:34
  • @user1330341: As that is not a jQuery method, it doesn't support the `deferred` object, but it would be possible to use one by creating it yourself. However, a `deferred` object only separates the callback method from the calling method in the code, you still have to handle the answer asynchronously. As you would have to create a `deferred` object manually to use one, there isn't really any point for you to do that. – Guffa Nov 10 '13 at 01:08