从函数的回调中返回变量 [英] returning a variable from the callback of a function
问题描述
我正在使用以下功能:
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屋!