Switching from callback to function in TypeScript

Currently, I am utilizing the mongodb driver to establish a connection with mongo:

 public listUsers(filterSurname?:string):any {

        if (this.connected) {
            debug.log(this.db);
            var results;
            this.db.collection('userProfiles').find({}).toArray((err:Error, res:any[])=> {
                if (err) return 'getting results error'
                else {
                    results=res;
                    results = res;
                }
                return res;
            });
        }

        debug.log('sending results' + results);
        if (results !== null) {
            return results;
        }
        else return 'connection error';

        return 'db unknown error'
    }

The function to array has the following signature:

toArray(callback: (err: Error, results: any[]) => any) : void;

I am looking for a way to return the value back to the function from the callback without adding another callback. Would there be an alternate solution or does TypeScript offer a resolution for callback hell?

Answer №1

To achieve your goal, you need to find a way to handle synchronous results from an asynchronous process, such as a database query.

There are several strategies you can use for this purpose:

Pass a callback function to the listUsers method

public listUsers(filterSurname?:string, 
  callback: (err: Error, results: any[])=>void):any {
  if (this.connected) {
        debug.log(this.db);
        var results;
        this.db.collection('userProfiles').find({}).toArray(callback);
    }
    debug.log('sending results' + results);
    if (results !== null) {

        return results;
    }
    else return 'connection error';
    return 'db unknown error'

}

Use a promise for handling asynchronous operations

There are various promise libraries available, with popular choices being Q and bluebird

Here is an example of using Q:

 public listUsers(filterSurname?:string): Q.Promise<any[]> {
   var defer = Q.defer(); // create the promise structure
   if (this.connected) {
     debug.log(this.db);
     this.db.collection('userProfiles')
       .find({})
       .toArray((err:Error, res:any[])=> {
         if (err) {
           defer.reject('error fetching results');
         } else {
           defer.resolve(res);
         }
       });
   }
   return defer.promise; // return the actual promise
 }

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

Forming a distinct array from a collection of objects

Describing demoList: demoList = [ { id: 1, validFrom: "2019-06-01T00:00:00", validTo: "2020-06-17T00:00:00", xxxM: 50, xxxN: 2.2, xxxQ45: 2, xxxQ100: 1.65, xxxQ125: null, xxxQ150: null, xxxQ2 ...

Query Morphia to filter and retrieve a nested list item

Just dipping my toes into the world of NoSQL and morphia. Currently exploring Morphia for querying MongoDB. Here's a glimpse of my sample collection: [ { "serviceId": "id1", "serviceName": "ding", "serviceVersion": "1.0", ...

Tips for showcasing individual row information in a popup window with Angular 9

Here is the code snippet for utilizing the open dialog method in the component: import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { AuthService } from '../_services/auth.se ...

Developing Angular 7 Forms with Conditional Group Requirements

I am currently in the process of developing a form that enables users to configure their payment preferences. The form includes a dropdown menu where users can select their preferred payment method. For each payment method, there is a FormGroup that co ...

Issue with Authentication - Sequencing of Observables and Promises in Angular/REST APIs

I'm currently utilizing Angular 7 and have recently started working on a new Angular application project at my agency. One of my colleagues has already set up the backend (Restful), so I began by focusing on implementing the Authentication Feature. T ...

The click event triggered by the onclick clone/function may not always activate the click handler

As a newcomer in the JavaScript domain, I am encountering an issue where the first clone created after clicking 'add more' does not trigger my click me function. However, every subsequent clone works perfectly fine with it. What could be causing ...

Populate List Items until Maximum Capacity is Reached and Increase the

Is there a way to make a ListItem fill the list vertically while also being able to overflow it if needed? I'm looking for a solution that would allow me to access the height of the empty space in the list, which I believe would be the minHeight. Som ...

Can you explain the purpose of the MomentInput type in ReactJS when using TypeScript?

I am currently facing an issue where I need to distinguish between a moment date input (material-ui-pickers) and a normal text input for an event in my project. const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => { const i ...

Iterate over every entry in mongoose and compare a designated column to elements in an array to determine the number of matches

As a newcomer to Mongo, I am facing a complex aggregation query that needs to be addressed. The goal is to iterate through each record and determine how many items from an array are present in a specific column. For example: If we have an array of tags th ...

Node's TypeScript parser loses the order of same name-tags when converting XML to JSON

I've experimented with xml2js and fast-xml-parser and received similar results from both (in different formats, but that's not the focus here) This specific example is from fast-xml-parser Here's the XML data: <test version="1" ...

Generating a slug string field from a name field with Mongoengine: A step-by-step guide

In my current Mongoengine model, I have defined a Movies class as follows: class Movies(BaseModel): movie_id = StringField(min_length=models.MOVIE_ID['MIN'], max_length=models.MOVIE_ID['MAX'], required=True) name = StringField( ...

Building a REST API in expressjs that is capable of accepting an array of resource id's is a straightforward process

When designing my MongoDB schema, I included an attribute like the following: . . . . tags: [{ type: String, required: true }], . . . . . I am looking to create an endpoint that retrieves all collections when a user requests multiple tags. How can I ach ...

Unable to position text in the upper left corner for input field with specified height

In a project I'm working on, I encountered an issue with the InputBase component of Material UI when used for textboxes on iPads. The keyboard opens with dictation enabled, which the client requested to be removed. In attempting to replace the textbox ...

What causes this conditional type to function correctly in a static context while failing in a dynamic setting

I have created a unique conditional type that accurately generates a union of valid array indices: type ArrayIndices< N extends any[], Acc extends number[] = [] > = Acc['length'] extends N['length'] ? Acc[number] : ArrayIn ...

Managing Keyboard Input in React using TypeScript

Hey there! I'm currently working on a method that should automatically insert a specific string into a textbox when a particular key is pressed. The key in question is a non-printable character that may not be visible in most font styles, but can sti ...

How can the data be accessed from a fulfilled promise returned by an async function?

Currently, I am delving into React and all things related to the MERN stack. My thirst for knowledge is insatiable and I aim to absorb as much as possible. Recently, I encountered an issue while attempting to retrieve todos from a database using the useSta ...

The error message "The type 'DynamicModule' from Nest.js cannot be assigned to the type 'ForwardReference' within the nest-modules/mailer" was encountered during development

Recently, I decided to enhance my Nest.js application by integrating the MailerModule. I thought of using the helpful guide provided at this link: Acting on this idea, I went ahead and performed the following steps: To start with, I executed the command ...

Tips for obtaining cookies within Nextjs api routes

I'm currently working on developing a note-taking application using Next.Js and MongoDB. The login system I have set up allows users to register for an account and login to start creating notes. To handle authentication, JWT is being utilized. Once a ...

PHP code for comparing two fields in a MongoDB collection using a query

There was a compilation of data, [ID] => 122344 [one] => Value 1 [two] => Value 2 [Session_id] => 73fdb9f3qf8gfejrv5e4nj0q22 [ses_id] => 73fdb9f3qf8gfejrv5e4nj0q22 [Date] => 2013-08-29 [ID] => 122345 [one] => Value 1 [two] => ...

Where can I find the Cypress.json file for Angular integration with Cypress using Cucumber?

We are currently transitioning from Protractor to Cypress utilizing Cucumber with the help of cypress-cucumber-preprocessor. While searching for Angular documentation on this setup, including resources like , all references lead to an automatically generat ...