Commit to calculating the total sum of each element using AngularJS

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.

Answer №1

If you find the promise concept challenging, another option is to utilize the new async await method (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function).

Furthermore, there exists the async module (https://caolan.github.io/async/docs.html) in JavaScript which offers a variety of methods like waterfall, specifically designed for your needs:

The waterfall function runs tasks in series, passing results from one function to the next in the array.

Answer №2

A possible implementation could look something like this:

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

    Promise.all(data.map(element) => {
        this.debugger.debugSomething("Reached : " + element as string);
        this.socialNetwork.api("/" + (element as string) + "?fields=likes", ["public_profile", "user_posts"])
    }).then((response) => {
        counter = response.reduce((sum, res) => {
            sum += res.likes.data.length ;
        }, 0);

        this.debugger.debugSomething(counter);
    }).catch((err) => {
        this.debugger.debugSomething(err);
    });

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discovering the generic parameter in the return type using TypeScript

I am struggling with a specific issue export type AppThunk<ReturnType> = ThunkAction< ReturnType, RootState, unknown, Action<string> >; After implementing the above code snippet export const loadCourse = (id: string): AppThunk ...

What could be causing this TypeScript class to not perform as anticipated?

My goal with this code snippet is to achieve the following: Retrieve a template using $.get(...), Attach an event listener to the input element within the template I am using webpack to transpile the code without encountering any issues. The actual cod ...

Looking to adjust the height of a foreignObject element within an SVG?

Looking to dynamically change the height of a foreignObject within an SVG, while also needing HTML elements inside it (working with ngx-graph). <foreignObject x="1" y="1" width="335" [height]="foreignObjHeight(node.Dat ...

External JavaScript files cannot be used with Angular 2

I am attempting to integrate the twitter-bootstrap-wizard JavaScript library into my Angular 2 project, but I keep encountering the following error: WEBPACK_MODULE_1_jquery(...).bootstrapWizard is not a function I have created a new Angular app using a ...

The preflight request in Angular2 is being rejected due to failing the access control check: The requested resource does not have the 'Access-Control-Allow-Origin' header

I encountered an issue while attempting to execute a basic POST request to establish an account using an API in .NET. The process fails with the mentioned warning title. Interestingly, performing the same request in Postman (an API testing tool) yields a s ...

Sorting and paginating the PrimeNG data table causes the webpage to automatically scroll to the top

Currently utilizing PrimeNG Datatable with pagination enabled. When attempting to sort a column or click on pagination buttons, the page automatically scrolls to the top. This behavior is due to the default href="#" in Primeng anchor tags. For example: & ...

What is the TypeScript syntax for indicating multiple generic types for a variable?

Currently working on transitioning one of my projects from JavaScript to TypeScript, however I've hit a roadblock when it comes to type annotation. I have an interface called Serializer and a class that merges these interfaces as shown below: interfa ...

Extracting information from an Observable in Angular: A comprehensive guide

I am currently working on an Angular application that interacts with a server through RESTful requests, and receives a JSON stream response containing objects of a specific type. The interface for these objects is as follows: export interface Personal { ...

Eliminating the need for RequireJS in the Typescript Visual Studio project template

After integrating RequireJS into my Typescript template using the nuget package manager, I found that it was more than what I needed and decided to uninstall it. Even though I removed the package through nuget and the files were deleted properly, my Typesc ...

The pipe seems to have malfunctioned

Here is how my pipe file appears: pipe.ts import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'unique', pure: false }) export class UniquePipe implements PipeTransform { transform(value: any, args?: any): any { ...

React waitforelement fails to work in conjunction with asynchronous calls

I am currently experimenting with a straightforward login form that includes an asynchronous call in React using TypeScript and classes. Here is how my component appears: import * as React from 'react'; import { LoginService } from './servic ...

Utilizing PropTypes in React with TypeScript

I've encountered issues while trying to integrate PropTypes with Typescript: Previously, without typescript, I had successfully used: class TodoFilterItem extends Component { constructor (props) { super(props); Followed by: TodoFilterItem.prop ...

API Routes - xxxx has been resolved by the API without sending back a response, potentially causing delays in request processing

While working on my frontend project, I encountered an issue with a simple API call using API routes. Whenever I try to complete the call, I face the following error which prevents my redirect from working: API resolved without sending a response for /ap ...

Exploring the benefits of using getServerSideProps with NextJS and Typescript for

Dear community, I am facing a challenge with integrating NextJS Layout and Typescript. Although everything seems to be working fine, I can't seem to get rid of the squiggly line under the props when passing them from getServerSideProps. The prop {som ...

What is the best way to add a custom typeguard to an object in TypeScript?

Looking to implement a type guard as an object method? I have an array of objects with similar data structures, but crucial differences that need to be checked and guarded using TypeScript. interface RangeElement extends Element { value: number; } inter ...

Ensure that the dynamically inserted <title> tag remains intact in Angular even when the page is re

Can the dynamic title tag be preserved when the page is refreshed? When I refresh the page, the title tag reverts back to the original one specified in the index.html temporarily before switching back to the dynamically added one. I want the title tag to ...

What is the process for obtaining the complete URL using the getDownloadURL() function along with a token?

An error occurred due to an unresolved FirebaseStorageError: "storage/object-not-found". The message indicates that the object 'k91a73uzb99' does not exist in Firebase Storage. This type of error is categorized under FirebaseError with a code of ...

Is it necessary for TrackBy to be a function in Angular 2, or can it be undefined?

Struggling with an error while developing a demo app in Angular 2. The error message reads: core.umd.js:3491 EXCEPTION: Uncaught (in promise): Error: Error in security.component.html:35:72 caused by: trackBy must be a function, but received undefined. Err ...

Using React MUI to implement a custom Theme attribute within a component

I have a CircularProgress element that I want to center, and to make the styling reusable, I decided to create a theme.d.ts file: import { Theme, ThemeOptions } from '@mui/material/styles' declare module '@mui/material/styles' { inte ...

Prevent selection of past dates and times in ng-bootstrap calendar in Angular 7

HTML <ngb-datepicker (select)="onDateSelect($event)" [(ngModel)]="datePickerModel"></ngb-datepicker> <ngb-timepicker [meridian]="meridian" [(ngModel)]="time" class="fromTimePick"> </ngb-timepicker> Is it possible to restrict the ...