我试图收集在循环中调用的FB API异步请求的结果。我用下一个代码:
function getPicturesByUserIds(friendsIdList) {
var userPictures = [];
for (var i = 0; i < friendsIdList.length; i++) {
(function () {
var userId = friendsIdList[i];
var j = i;
var friendsIdListLength = friendsIdList.length - 1;
FB.api('/'+userId+'/picture?type=large', function (responce) {
if (responce && !responce.error) {
userPictures[userId] = responce.data.url;
}
if (j >= friendsIdListLength) {
console.log(userPictures);
sendPicturesAndGetResponse(userPictures);
}
});
})();
}
}
此代码适用于Chrome,但在Firefox数组中,userPictures为空。
您可以使用“递归函数”解决这类问题,或者 - 更好 - 只需使用一个API调用:
/me/friends?fields=name,picture.type(large)
我会计算递归函数到编程的基础知识,你应该熟悉这些。例如:Calling a javascript function recursively