使用javascript我得到了facebook好友列表,虽然它现在只返回name和id,但我需要获取每个用户的图片。我尝试循环响应,然后尝试调用api来获取图片,但由于它是异步调用,我无法将返回的图片与数组中朋友的索引相关联。 *这有点像我在异步编程中遇到的问题,是否有标准模式?
实施例
FB.api('me/friends', function(response) {
if(response.error == null){
var friendsSale = response.data;
var len = friendsSale.length;
for(var x=0; x<len; x++){
FB.api(friendsSale[x].id+'/picture', function(response) {
//x no longer is the same x as the initial call, and I can't pass in the orignal array object into the FB.api function to return as part of the response... or can I?
friendsSale[x].pictureUrl = response;
});
}
}
//Then how do I know when I have all the pictures set so I can then set datamodle with the complete friend array?
m.friends(friendsSale);
}
});
答案 0 :(得分:2)
简单的解决方案:
您所要做的就是查询:
https://graph.facebook.com/user_id/picture
你会得到用户个人资料图片。例如:
查询https://graph.facebook.com/4/picture
(没有访问令牌BTW - 尝试使用chrome pron 隐身模式):
<img src="https://graph.facebook.com/4/picture">
现在你知道Marks fbid:P
答案 1 :(得分:2)
是的,有一种模式:Closure
...
var len = friendsSale.length;
for (var i = 0; i < len; i++) {
(function() {
var j = i;
FB.api(friendsSale[i].id+'/picture', function(response) {
friendsSale[j].pictureUrl = response;
});
})();
}
要知道所有呼叫何时返回,您只需保留一个返回呼叫的计数器,例如
...
var len = friendsSale.length;
var returnedCallsCounter = 0;
for (var i = 0; i < len; i++) {
(function() {
var j = i;
FB.api(friendsSale[i].id+'/picture', function(response) {
friendsSale[j].pictureUrl = response;
// Track number of returned calls
returnedCallsCounter++;
// Check if all calls have returned
if (returnedCallsCounter == len) {
m.friends(friendsSale);
}
});
})();
}