0

I'm pretty confused by the JavaScript scoping. I have a call to FB.api (shown below) that I would like to return a response object:

(function() {
    var permissions;

    FB.api("/me/permissions", "get", {access_token: options.token}, function(r) {
        permissions = r;
    });

    console.log(permissions);
})();

Ideally, I'd like to assign FB.api to a variable, and use the anonymous function to return the r component, but it appears like that's not doable.

Why is permissions undefined? Is there a way to set permissions in the parent scope?

Eric Keyte
  • 633
  • 5
  • 14
  • 3
    FYI, the problem is not scope, but timing. You are calling `console.log(permissions)` **before** `permissions = r;` is executed. This is probably one of the most asked questions here. – Felix Kling Dec 06 '14 at 20:15
  • Ah, thanks Felix. I appreciate it. Is there a good resource for teaching users how to manage this? I'm not sure what I should be using for search terms. Many thanks! – Eric Keyte Dec 07 '14 at 00:55
  • 1
    Have a look at the duplicate questions. Searching for "asynchronous JavaScript" should also yield results. Solutions are "callbacks" and especially "promises". – Felix Kling Dec 07 '14 at 00:57
  • Thanks Felix, you've helped tremendously. – Eric Keyte Dec 12 '14 at 23:39

0 Answers0