如何循环通过我/朋友,并从FB.api的{USERID} /图片分配每个用户的图片 [英] How to loop through me/friends and assign each user it's picture from {USERID}/picture from FB.api
问题描述
使用javascript我得到Facebook的朋友的列表,虽然它只返回名称和id现在,但我需要获取每个用户的图片。我尝试循环响应,然后尝试调用api来获取图片,但是由于它是异步调用,我无法将返回的图片与数组中的朋友的索引相关联。 *这是一个与异步编程一般的问题,是否有一个标准模式?
Using javascript I get list of facebook friends though it only returns name and id now, but I need to get the picture of each user. I try to loop through the response and then try to call the api to get picture, but due to it's async call I can't associate the returned picture with the index of the friend in the array. *this is kinda a problem that I've had with asynchronous programming in general, is there a standard pattern for this?
示例。
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);
}
});
推荐答案
是的,有一个模式: a href =https://developer.mozilla.org/en/JavaScript/Guide/Closures =nofollow>关闭
Yes, there is a pattern for this: a 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;
});
})();
}
要知道所有的所有呼叫都已经返回,您可以简单地保留返回的计数器电话,例如
To know when all all calls have returned you can simply keep a counter of returned calls, e.g.
...
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);
}
});
})();
}
这篇关于如何循环通过我/朋友,并从FB.api的{USERID} /图片分配每个用户的图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!