从函数的回调中返回变量 [英] returning a variable from the callback of a function

查看:99
本文介绍了从函数的回调中返回变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下功能:

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;
    }

现在,问题是我从check_perm的结果中得到了undefined,而在Firebug控制台中,我可以看到response的值为0或1(取决于烫发)

有人知道我在做什么错吗?我想这与我试图在回调中捕获变量的值有关.

问候 尼基尔·古普塔(Nikhil Gupta).

解决方案

我认为Facebook API是异步的.因此,在执行return result时,尚未调用该回调.您必须提供来自调用函数的回调:

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

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆