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

Tips for handling catch errors in fetch POST requests in React Native

I am facing an issue with handling errors when making a POST request in React Native. I understand that there is a catch block for network connection errors, but how can I handle errors received from the response when the username or password is incorrec ...

Typescript - Issue with accessing Express Response object

Having trouble using the methods of the Response object in my TypeScript method. When I try to log it, all I get is an empty object. It seems like the import is not providing the response as expected. import { Response } from 'express'; async sen ...

Dealing with numerous dynamically generated tables while incorporating sorting in Angular: a comprehensive guide

I am faced with a challenge involving multiple dynamically created Angular tables, each containing the same columns but different data. The issue at hand is sorting the columns in each table separately. At present, I have two tables set up. On clicking the ...

Trouble arises when attempting to remove an object using a combination of Node.JS, Mongoose, MongoDB, and

In my setup, I have two collections: one is called subcategories and the other is called categories. The categories collection includes a field known as subcategories which is an array containing the ids of the subcategories from the subcategories collecti ...

VSCode prioritizes importing files while disregarding any symbolic links in order to delve deeper into nested node

I'm encountering a problem with VSCode and TypeScript related to auto imports. Our application includes a service known as Manager, which relies on certain functions imported from a private npm package called Helpers. Both Manager and Helpers make us ...

Encountered an error stating 'name' property is undefined while using @input in Angular 2

Everything seems to be set up correctly, but I'm encountering an error in the browser console that says "Cannot read property 'name' of undefined": This is how my media.component.ts file is structured: import { Component, Input } from &apo ...

What distinguishes between a public variable declared as var: any = []; versus a public variable declared as var: any[] =

I'm seeking clarification on the distinction between the following: public var: any = []; // versus public var: any[] = []; ...

Contrasting the utilization of `typeof` with a constant and `enum` in TypeScript

Can you explain the distinction between using typeof with a constant and an enum in TypeScript? For example: const TYPE_A = 'a' const TYPE_B = 'b' type MyType = | typeof TYPE_A | typeof TYPE_B type Result = { name: string type ...

Simulated FileList for Angular 5 App Unit Testing

Imitation FileList In my pursuit of writing a unit test (Angular5), I have encountered the need for a FileList. Despite researching extensively, I have been unable to uncover any clues or solutions. I am starting to question whether this is even feasible ...

Is there a way to execute a code snippet just once when focusing on a specific field?

<form id="myForm"> <label for="fname">First name:</label><br> <input type="text" id="fname" name="fname"><br> <label for="mname">Middle name:</label> ...

When searching through a mongodb model's array in mongoose, I aim to identify records that have the highest number of matches within that array

My mongoose schema looks like this: const userSchema = new mongoose.Schema({ keywords: [{ "type": String, "enum": ["yup", "nope"] }], }) In this schema, each user has a set of keywords and I want to find records in my database that have the most similar ...

A simple trick to compile and run TypeScript files with just one command!

Converting TS to JS is typically done using the tsc command, followed by executing the resulting .js file with node. This process involves two steps but is necessary to run a .ts file successfully. I'm curious, though, if there is a way to streamlin ...

Conceal dynamically generated div elements created with ngIf

I am currently working on initializing this div using ngOnInit in Angular ngOnInit(): void { let optTemp = ''; for (let data of arrOption) { optTemp = optTemp + '<option>' + data.trim() + '</option> ...

Problems encountered when utilizing $in operator in Mikro ORM MongoDB operations

For my project, I'm utilizing mikro orm with MongoDB to handle database operations in TypeScript. So far, it has proven to be the most effective ORM for MongoDB in this language. However, I've encountered type errors when using $in with Object ID ...

Halt of dispatcher playback occurs after a duration of 10 minutes with discord.js

Currently, I've been working on a music bot using discord.js. To handle audio streaming, I'm utilizing @discordjs/opus and ytdl-core-discord. Everything runs smoothly when testing the bot locally on my machine - songs from YouTube are played with ...

Error message "Undefined is not a constructor" can occur when using Ionic2 with Karma and Jasmine

I'm facing a challenge while trying to create tests for an Ionic2 App using Karma + Jasmine. I encountered a runtime error and, given my lack of experience, I'm having trouble pinpointing the actual issue. Here is my setup: test.ts This file con ...

The output is displayed on the console, but it cannot be stored in a variable

var x = ""; Promise.all(listOfItems).then(function(results) { for (let j in results) { var newitem = results[j]; x = newitem; console.log(`x: ${x}`); } }); The output on the console displays x: "val ...

Best Practices for Integrating Angular with Your Custom JavaScript Library

Imagine needing to create a TypeScript function that can be utilized across various components, services, or modules. For example, let's say you want an alert wrapper like this: my_alert(msg); // function my_alert(msg) { alert(msg); } You might hav ...

Tips for restricting nested object in MongoDB aggregation query

Currently, I am working on a nodeJS service using Express with MongoDB as the Database. The documents contain nested objects and I am looking to implement pagination for the aggregation of nested lists. The format of my documents is as follows: { &quo ...

What is the best way to retrieve both the checked and unchecked values from a collection of checkboxes?

Check Out This live Example: I am in the process of creating a list of checkboxes with various data objects: data = [ { Key: "class_id", displayName: "Section ID", enabled: true }, { Key: "room_l4", displayName: "Location", enabled: false }, { Key: "se ...