Using the return statement to set a value from a callback function in TypeScript

As I retrieve data from an array of class People, each person has an attendance list represented by Observable<any[]>.

// Defining the Person class
class Person {
   id: number;
   name: string;
   attendance: Observable<any[]>; // Represents an Observable array
}

// Creating an array of People (for simplicity)
people = Person[] = this.someService.getPeople(); 

My current task involves checking if any individuals in the group have an empty attendance list, assuming that

attendance: Observable<any[]>
will be an empty array [] when no data is found. The goal is to return true or false depending on the outcome of the validation within the validateAttendance() method.

validateAttendance(): boolean {

    // Loop through each person in the array to access their attendance list.
    people.forEach(p => {
       // Using a callback function to retrieve the list.
       const func = (callback: (data) => void) => {
            // Subscribing to get the attendance data
            p.attendance.subscribe(list => {    
                callback(list);
            });
        }

       // Attempting to retrieve and check the list using the callback function
       // The issue arises as the 'result' variable turns out to be undefined.
       const result = func(res => {
           console.log(res); // Displays the attendance list for a given person
           return res;
       });

       if (result.length <= 0) {
           alert(`${p.name} has no attendance recorded - they might need a gentle nudge!`);
           return false;
       }
    });

    return true;
}

To resolve this, I experimented with incorporating a callback function inside the validateAttendance() method to obtain the attendance list and return it. Unfortunately, the 'result' variable remained undefined!

Is there a way to successfully return a value from a callback function in this scenario?

Answer №1

Here are a few issues with your current code:

  1. The code is asynchronous, so the function should also be async using Promise.
  2. The func() does not return a value, resulting in the result always being undefined.
  3. You have an alert() call within your logic. This may cause multiple pop-ups for each person without attendance, it's better to separate logic and UI concerns.

I've made some modifications to your code as follows:

function validateAttendance(people): Promise<boolean> {
  return getPeopleWithNoAttendance(people)
    .then(peopleWithNoAttendance => {
      if (peopleWithNoAttendance.length > 0) {
        // or loop through them
        alert(`${peopleWithNoAttendance[0].name} has no attendance, must be a lazy one please check.`);
        return false
      }
      return true
    })
}

function getPeopleWithNoAttendance(people) {
  return Promise.all(people.map(person => {
    return new Promise(r => {
      person.attendance.subscribe(r)
    }).then(attendance => {
      return attendance.length <= 0 ? person : undefined
    })
  })).then(listOfPeopleOrUndefined => {
    const listOfPeople = listOfPeopeleOrUndefined.filter(p => p)
    return listOfPeople
  })
}

Additionally, I've updated the code to pass the people variable. If this function belongs within a class, you can make adjustments accordingly.

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

Exploring advanced routing concepts in Angular 2

I have a challenge in setting up routing in angular 2 with the following scenario home.component: @RouteConfig([ { path: '/', name: 'Home', component: HomeComponent }, { ...

Ensure that each function is completed before proceeding to the next one

I've encountered an issue with my react app. After a user submits a form, I need a modal to open and the user's response to be stored in state. Then, based on this response, I have to execute some business logic before finally submitting the form ...

Is HTML-escaping necessary when implementing regex checks?

As I develop a web application that takes user input through HTML inputs and forwards it to my tomcat server for processing, my current workflow is as follows: Client JS -> collect HTML input -> perform regex validation -> if successful -> send data via ...

A guide on utilizing the useEffect hook to dynamically update a button icon when hovering over it in a React application

Is it possible to change the icon on a button when hovering using useEffect? <Button style={{ backgroundColor: "transparent" }} type="primary" icon={<img src={plusCart} />} onCl ...

Converting JSON data into objects in JavaScript

My task involves processing a large JSON list with over 2500 entries, formatted as follows: [ ['fb.com', 'http://facebook.com/'], ['ggle.com', 'http://google.com/'] ] This JSON list represents pairs of [&ap ...

A new module is unable to load Angular Material

Recently, I developed an Angular material module similar to a core module. import { NgModule} from '@angular import {MatCheckboxModule} from '@angular/material/checkbox'; @NgModule({ imports: [ MatCheckboxModule ], exports: [ ...

Manipulating a global variable in VueJS

Currently, I am referring to Global data with VueJs 2 for my project, focusing on only one variable. In the code provided, I have included an @click event to update the variable. However, it throws an error stating "Uncaught ReferenceError: $myGlobalStuff ...

Determining the selected option's value made by the user

On my index.php file, which contains the form and function, I have the following code: $(function() { $.ajax({ type: "POST", url: "invtype.php", data: "getrevenuetype=true", success: function(b){ $("#revenue ...

Experiencing difficulty importing Materialize CSS JS into React

Good day everyone, I've been facing challenges in implementing materialize css into my react-app, specifically with the JavaScript files. After trying various methods, I believe that I have made some progress using the following approach: In my &ap ...

What could be causing the div to be wider than the content inside of it?

I am having an issue creating a webpage with a 20-60-20 flex fill layout. The div in the center, which should occupy 60% of the page, is wider than its content, causing it to appear off-center. https://i.stack.imgur.com/WwCJy.png Here is my home.componen ...

How to bind parent object scope to MySQL query's anonymous callback in Node.js

As a newcomer to node.js, I am still working on understanding the concept of scoping anonymous functions. I have created an object with multiple methods and within one of my methods, I retrieve a MySQL connection from a pool and then execute a query on tha ...

What is the best way to properly format letters with accents (such as French letters)?

I have encountered a challenge where I created a PHP file to display French text and then utilized this text in an AJAX file (specifically the responseText). The issue arises when trying to show the French responseText in an alert using JavaScript, as ac ...

Exploring discrepancies in jQuery AJAX responses between Chrome and Firefox

As someone who is not a front-end developer, I find myself working on a casual project that involves using AJAX to retrieve a piece of JSON data. $('#btn1').click(function() { $.ajax({ url: 'http://mywebsite.com/persons/mike&apo ...

Best practices for effectively managing a sizable dataset in Vue.js

My task at hand is to create a visualization dashboard that can operate solely in the browser, utilizing Vue.js, D3, and JavaScript. The dataset I am working with is stored in a .json file that is 48 MB in size. However, upon parsing the file using d3.json ...

What steps should be taken to refresh an Expo app block once new data is retrieved from the database

I'm facing an issue with connecting my expo app to a database. I have utilized react redux to fetch data from the database, and upon successful retrieval of data, I aim to update my furniture block with the obtained information. However, despite recei ...

The 'Group' type is lacking the 'children' properties needed for the 'Element' type in Kendo UI Charts Drawing when using e.createVisual()

In my Angular 10 project, I utilized the following function to draw Kendo Charts on Donut Chart public visual(e: SeriesVisualArgs): Group { // Obtain parameters for the segments this.center = e.center; this.radius = e.innerRadius; // Crea ...

Test your word skills with the Jumbled Words Game. Receive an alert when

After reviewing the code for a jumble word game, I noticed that it checks each alphabet individually and locks it if correct. However, I would like to modify it so that the entire word is only locked if all the letters are correct. Any suggestions on how t ...

Understanding AngularJS and how to effectively pass parameters is essential for developers looking

Can anyone help me figure out how to properly pass the html element through my function while using AngularJS? It seems like this method works without AngularJS, but I'm having trouble with the "this" keyword getting confused. Does anyone know how I c ...

Is there a way to retrieve the same post from one controller and access it in another?

Hello, I am currently exploring the world of Full Stack web development and have stumbled upon a challenge. My tech stack includes mongodb, mongoose, node, and express. Within my project, I have implemented two controllers - one for user signup and anothe ...

Is there a method to refresh the image in the template?

I am currently working on generating various images using canvas. Is there a way to display these images in real-time on my main.pug template without having to reload the page every time an image changes? const Canvas = require('canvas') , Ima ...