0

I'm using Angular 2 with TypeScript and experimenting with a Facebook SDK wrapper.

I need to resolve the Facebook data in a loop. Somehow my promise array is not resolving. But when I log the response from the api call, everything seems fine. So I'm doing something wrong with the Promise handling.

Promise function:

getOrgData(): Promise<any> { // I ONLY NEED TO STORE THE ORGANISATION IDS, DONT NEED FB API FOR THAT ... ??? I DO NEED THE CATEGORIES, PLACE_TOPICS, EMAILS, ...
  let promiseArray: Array<any> = []
  for (var o in this.per50) {
    promiseArray.push(new Promise((resolve,reject) => 
      this._facebookService.api('/?ids=' + this.per50[o] + '&fields=id,name,category,category_list,place_topics,place_type,emails,phone,location&access_token='+ this.access_token)
      .then(
        (resp) => {
          console.log(resp);
          resolve(true)
        },
        (error) => this.errorMessage = error
      )
    ));
  }

  return Promise.all(promiseArray);
}

And I'm calling it like this:

this.getOrgData().then(
  resp => console.log(resp),
  error => console.log(error),
)

The reason of the for loop is that a Facebook api call can only handle 50 items at a time so I had to make an object containing an array of maximum 50 items.

So foreach array of 50 I'm doing a Facebook call. All that works fine ... It's just that the Promise array doesn't seem to get resolved. Anyone got an idea ?

I'm not really experienced with Promises and I'd prefer Observables but this Facebook SDK Wrapper works with Promises so ...

---------------------------SOLVED----------------------------

Apparently the promises were working fine but I didn't catch the errors of the Facebook Api call so I never got in the then() of the Facebook call so no resolving was happening, my bad.

1 Answers1

0

use let instead of var in you for loop

for (let o in this.per50) {
    promiseArray.push(new Promise((resolve,reject) => 
      this._facebookService.api('/?ids=' + this.per50[o] + '&fields=id,name,category,category_list,place_topics,place_type,emails,phone,location&access_token='+ this.access_token)
      .then(
        (resp) => {
          console.log(resp);
          resolve(true)
        },
        (error) => this.errorMessage = error
      )
    ));
  }
El houcine bougarfaoui
  • 35,805
  • 9
  • 37
  • 37