我正在尝试收集在循环中调用的 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 中 array userPictures 为空。
最佳答案
您可以使用“递归函数”解决此类问题,或者 - 更好 - 只需调用一个 API 即可:
/me/friends?fields=name,picture.type(large)
虽然我会将递归函数算作编程的基础知识,但您应该熟悉它们。例如:Calling a javascript function recursively
关于javascript - 如何循环收集来自 Facebook API 请求的响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35367016/