callback on a variable which is inside a .each() loop
I have this function, which is doing an asynchronous call to FB.api method. Now, i am looping over some data and capturing result of the above method call successfully.
However, I am using a.each
loop and I really can not figure out how to place my callback in this method, so that the outer method is only executed once.
Here are the functions I am using:
ask_for_perms($(this).val(),function(result) {
$('#some-div').html('<a onclick = "get_perms(result);" >get perms</a>');
});
function ask_for_perms(perms_requested,cb) {
var request = [];
$.each(perms_requested,function(i,permission) {
FB.api({
method: 'users.hasAppPermission',
ext_perm: permission
}, function(response) {
if (response == 0) request.push(permission);
request.join(',');
cb(request); // cb is called many times here.
});
});
}
I am trying to return t开发者_开发知识库he request
string from ask_for_perms
function.
Can anyone suggest me on where to place a proper callback to ask_for_perms
. Right now, however, it works for me, but the callback is being called many times since it is inside a for loop.
referencing: returning a variable from the callback of a function
This is happening because you FB calls are asynchronous and you call cb(request) before they are able to execute their callbacks. Try checking for the last requested response, then calling your cb function:
function ask_for_perms(perms_req,cb) {
var request = [];
$.each(perms_req,function(i,req) {
FB.api({
method: 'users.hasAppPermission',
ext_perm: req
}, function(response) {
console.log(req + ' | ' + response);
if (response == 0) {
request.push(req);
if(i == perms_req.length-1) //true if last item in array
cb(request.join(','));
}
});
});
}
精彩评论