简体   繁体   中英

returning a variable from the callback of a function

I am using the following functions:

function loop_perms(permissions) {
.... call check_perm here....
}
function check_perm(perm) {
        var result;
        FB.api(
         {
            method: 'users.hasAppPermission',
            ext_perm: perm
         }, function(response) {
            result = response;
         });
         return result;
    }

Now, the issue is that I am getting an undefined from the result of check_perm whereas in the Firebug console, I can see that response has a value of 0 or 1 (depending on perm)

Anyone knows what I am doing wrong? I am guessing it has something to do with the fact that i am trying to capture the value of a variable inside a callback.

Regards Nikhil Gupta.

I assume the Facebook API is asynchronous. So at the time return result is executed, the callback was not called yet. You have to provide a callback from the calling function:

function check_perm(perm, callback) {
    var result;
    FB.api(
     {
        method: 'users.hasAppPermission',
        ext_perm: perm
     }, callback);
}

and

function loop_perms(permissions) {
    check_perm(whatever here, function(result) {
        // do something with result
    });
}

It looks like you're calling FB.api asychronously, passing it an anonymous function as a callback that gives result a value. check_perm is returning before the callback is executed, at which point result is still undefined.

Problem 1: result is readable by the callback, but it is a copy so not writeable in the way you're thinking. (writeable locally not globally, this sub-problem could be "fixed" by making it a global variable, but it still wouldn't make your code work)

Problem 2: FB.api most likely calls that callback asynchronously in the future letting check_perm return immediately with result in whatever state it currently is in (undefined)

You need to put the code that deals with the actual response inside that callback function to be executed when then response is available. You wouldn't even need the result variable at that point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM