Facebook API callback on response
I have a problem with the Facebook API. I may not be g开发者_如何转开发oing the about this the best way, but here is what I've got.
I have a array of request_ids, which I need to convert to user Ids. I have a while loop which queries the request ids and gets the user id.
function (response) {
var requestsToSend = new Array();
var i = 0;
while (i < response.request_ids.length)
{
FB.api('/'+response.request_ids[i], function(res){
requestsToSend[i] = res['to']['id'];
});
i++;
}
console.log(requestsToSend[0], requestsToSend[1], requestsToSend[2], requestsToSend[3]);
}
This works fine. However, when I echo the returned ids (console.log) they are undefined, because the FB.api
hasn't yet returned the values/responses.
Is there any way to fire the console.log
only once the FB.api
has returned values?
I don't really want to set a timer to fire the function.
Put your console.log call in the response function:
function (response) {
var requestsToSend = new Array();
var i = 0;
while(i < response.request_ids.length) {
FB.api('/'+response.request_ids[i], function(res){
requestsToSend[i] = res['to']['id'];
console.log(requestsToSend[i]);
});
i++;
}
}
Iv fixed the issue but not very happy with the solution
function (response) {
var requestsToSend = new Array();
var i = 0;
var arry = new Array();
FB.api('/'+response.request_ids[0], function(res){
if(typeof res['to'] != 'undefined'){
useResults(res['to']['id']);
}
});
FB.api('/'+response.request_ids[1], function(res){
if(typeof res['to'] != 'undefined'){
useResults(res['to']['id']);
}
});
FB.api('/'+response.request_ids[2], function(res){
if(typeof res['to'] != 'undefined'){
useResults(res['to']['id']);
}
});
FB.api('/'+response.request_ids[3], function(res){
if(typeof res['to'] != 'undefined'){
useResults(res['to']['id']);
}
});
function useResults(value){
arry.push(value);
timeToFire(arry);
}
function timeToFire(arry){
if(arry.length == response.request_ids.length){
//console.log(arry);
playTheGame(arry[0], arry[1], arry[2], arry[3]);
}
}
}
精彩评论