Javascript Facebook API响应回调
我对Facebook API有问题。我可能不会用最好的方法来解决这个问题,但这就是我所拥有的 我有一个请求ID数组,需要将其转换为用户ID。 我有一个while循环,它查询请求id并获取用户idJavascript Facebook API响应回调,javascript,jquery,ajax,facebook,facebook-graph-api,Javascript,Jquery,Ajax,Facebook,Facebook Graph Api,我对Facebook API有问题。我可能不会用最好的方法来解决这个问题,但这就是我所拥有的 我有一个请求ID数组,需要将其转换为用户ID。 我有一个while循环,它查询请求id并获取用户id function (response) { var requestsToSend = new Array(); var i = 0; while (i < response.request_ids.length) { FB.api('/'+resp
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]);
}
这个很好用。但是,当我回显返回的ids console.log时,它们是未定义的,因为FB.api尚未返回值/响应
是否有任何方法仅在FB.api返回值后触发console.log?
我真的不想设置计时器来启动该函数。将您的console.log调用放入响应函数:
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解决了问题,但对解决方案不太满意
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]);
}
}
}
我认为res是一个对象,你使用res作为数组。我知道你的建议是有效的,但它对我没有帮助。我知道要返回的值是什么,但一旦它们全部返回,我就需要使用它们。因此,首先定义一个数组来存储它们,比如:var finalRequests=[],然后将示例中的console.log代码替换为:finalRequests.pushrequestsToSend[I],当代码从while循环的底部退出时,您将有一个随时可用的请求数组。