2

I am trying to collect results of FB API asynchronous requests which are called in loop. I use next code:

    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);
                    }
                });
            })();
        }
    }

This code works in Chrome, but in Firefox array userPictures is empty.

Cœur
  • 32,421
  • 21
  • 173
  • 232
Network_SPY
  • 243
  • 2
  • 9
  • `userPictures` should be an object (since you're keying using the userID), or you should be using the index `i`. That aside, your loop keep resetting `userID`, so all of your callbacks are dereferencing the same value - you actually want to pass the userID or iterator in via the `(function(id) {....}(id))` call you have to avoid this – Sean Kinsey Feb 16 '16 at 18:01

1 Answers1

1

You can solve those kind of things with "recursive functions", or - better - just use one API call for it:

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

I would count recursive functions to the basics of programming though, you should get familiar with those. For example: Calling a javascript function recursively

Community
  • 1
  • 1
luschn
  • 68,448
  • 8
  • 104
  • 118