0

I am trying to loop through an array organization and make a call to the Facebook API to return a Facebook ID.

The loop works great for looping through the values to make the API call and I get the response okay. But when I try to store response back into organization[i].fbid I get an error:

Cannot set property 'fbid' of undefined.

It seems that by the time that line executes that value of i has already incremented past what I have defined already. Is there a better method than the loop for this? Or is there a way to use the value of i within that particular Facebook API call so I can store back all data to appropriate array.

for (var i = 0; i < organization.length;i++) { 
  FB.api(organization[i].url, function(response){
    console.log(response); //Ok here, responds with correct FacebookID
     organization[i].fbid = response.id; // Get an undefined here
    }) 
} 

Update: In case anyone reads this, the solution worked via the link provided. Sorry for the dupe.

var funcs = [];
  function getEventInfo() {
   for (let i = 0; i < organization.length;i++) { 
        funcs[i] = function() {
        FB.api(organization[i].url, function(response){
         organization[i].fbid = response.id;
         organization[i].fbname = response.name;
         console.log(organization);
         }) 
        }
        funcs[i]();
      } 
    }
Mark
  • 1
  • 1
  • 1
    `FB.api` is asynchronous. `i` will equal `organization.length` when the loop is finished. The callback functions will run after the loop is finished. – Sebastian Simon Nov 20 '17 at 20:33
  • Have a look into asynchronous looping. One that I would recommend is the [async library](http://caolan.github.io/async/) and `async.each()` – Matt Fletcher Nov 20 '17 at 20:37

0 Answers0