Trying to implement a like counter using Facebook's GRAPH API. I have a list of object IDs and for each ID, I make an API call to retrieve the number of likes and calculate a total.
The issue arises as the API call returns a promise, causing only one call to be reached in the forEach loop, even with multiple elements in the list.
How can I correctly sum up the likes? Below is my code:
countLikes(data: any[]) {
let counter: number = 0;
data.forEach(element => {
this.debogger.debugSomething("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.debugSomething(counter);
}).catch((err) => {
this.debogger.debugSomething(err);
});
});
}
This is my first post on Stack Overflow! Thank you!
**[EDIT] New code, still not functional:**
countLikes() {
Promise.all(this.objectIdsToFilter.map((value) => {
return this.facebook.api(value + "?fields=likes", ["public_profile","user_posts"])
}))
.then((response) => {
this.debogger.debugSomething(response)
})
.catch(err=>{
this.debogger.debugSomething(err);
})
}
An input array contains 3 values (2 valid, 1 invalid). The output shows nothing happening, which is strange since the debugger should pop-up.