skip to Main Content

I’m trying to set a counter of likes using facebook’s GRAPH API.
I have a list of object ids, and for earch ID, I use an api call to get how many likes this object got, then set a sum.

But this call is returning a promise, and when I’m using foreach, only one call is rearched even if I have more than one element in my list.

How can I do this to get this summation ?
Here’s my code.

countLike(data : any[]){
  let counter : number = 0;

  data.forEach(element => {
    this.debogger.debogSomething("Reached : " + element as string);
      this.facebook.api("/"+ (element as string) +"?fields=likes", ["public_profile","user_posts"]).then((response) => { 
        counter += response.likes.data.length as number;
        this.debogger.debogSomething(counter);  
    }).catch((err) => {
      this.debogger.debogSomething(err);
    });
  });
}

It’s my first post in stackoverflow!
Thank you so much !

**[EDIT] new code, still not working **

countLike(){
  Promise.all(this.objectIdsToFilter.map((value) => {
    return this.facebook.api(value+"?fields=likes", ["public_profile","user_posts"])
  }))
  .then((response) => { 
    this.debogger.debogSomething(response)
  })
  .catch(err=>{
    this.debogger.debogSomething(err);
  })
}

In input, an array contains 3 values, (2 valids, 1 invalid).
The output : nothing happens (weird, the debogger is a pop-up).

2

Answers


  1. You can probably do something like below:-

    countLike(data: any[]) {
        let counter: number = 0;
    
        Promise.all(data.map(element) => {
            this.debogger.debogSomething("Reached : " + element as string);
            this.facebook.api("/" + (element as string) + "?fields=likes", ["public_profile", "user_posts"])
        }).then((response) => {
            counter = response.reduce((sum, res) => {
                sum += res.likes.data.length ;
            }, 0);
    
            this.debogger.debogSomething(counter);
        }).catch((err) => {
            this.debogger.debogSomething(err);
        });
    
    }
    
    Login or Signup to reply.
  2. You can also use the new async await method (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) if the promise concept is difficult for you.

    Also there’s this async module (https://caolan.github.io/async/docs.html) which you can use in js that has several methods such as waterfall which is exactly what you need, as the author says:

    Runs the tasks array of functions in series, each passing their results to the next in the array.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search