如何收集来自 Facebook API 循环请求的响应?

How to collect responses from Facebook API requests in loop?

我正在尝试收集在循环中调用的 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 为空。

您可以使用 "recursive functions" 解决此类问题,或者 - 更好 - 只需使用一个 API 调用即可:

/me/friends?fields=name,picture.type(large)

虽然我会将递归函数算作编程的基础知识,但您应该熟悉它们。例如:Calling a javascript function recursively