Callback does not modify the value

I am attempting to retrieve a result from a series of callback functions, but I am encountering an issue where no result is being returned at all.

Below is the code snippet I am working with:

Main function :

let userldap:userLDAP = {controls:[],objectClass:[],dn:"",sn:"",givenName:"",mail:"",uid:"",cn:"",userPassword:""};
let res:ldapRes = {err:"",info:"",user:userldap};

this.ldap.authentication(credentials,res);

Essentially, I am trying to modify the values in the `res` object.

Service :


  public authentication(
    credentials: Credentials,
    res:ldapRes,
  ):void {
    this.ldap.authenticate(credentials.username, credentials.password,function(err:string,user:any,info:string) {
          res.err = err;
          res.info=info;
          res.user=user;
      });
  }

This appears to be a very basic usage scenario. However, the callback within the `authenticate` function does not seem to update the `res` object.

I have tried several approaches such as using global context, but the callback in the `authenticate` function continues to reset the object to its original value after modification.

If anyone has insight into what may be causing this issue (it appears to be a simple problem related to variable scope, although I am unable to find a solution), I would greatly appreciate your input :) .

Thanks.

EDIT : Despite attempts including using `await` on the callback within the `auth` function, the issue persists:

public async authentication(credentials : Credentials, res: ldapRes):Promise<ldapRes>{
    //console.log(res);
    await this.ldap.authenticate(credentials.username, credentials.password, function(err:string,user:any,info:string) {
      res.err = err; res.info=info; res.user = user;
      console.log("Callback from inside auth function :");
      console.log(res);
    });
    console.log("Callback from outside auth function :");
    console.log(res);
    return res;
  }

In this case, the logging within the function works as expected, while the external log still displays a reset version of `res` (no values).

Answer №1

We came to understand the correct approach. Our misunderstanding revolved around the Promise concept in Typescript. It turns out that a promise can be returned in a function, not just the User object.

Here is the main function:

async verifyCredentials(credentials: Credentials): Promise<User> {
    let proms = new Promise<User>(function(resolve,reject){
      ldap.authentication(credentials).then(val => {
        let foundUser : User = new User();
        foundUser.email = val.user.mail;
        foundUser.firstName = val.user.givenName;
        foundUser.lastName = val.user.sn;
        foundUser.id = val.user.uid;
        resolve(foundUser);
      }) 
    })
    return proms;
  }

Now, take a look at the LDAP function:

public async authentication(
    credentials: Credentials,
  ){
    return new Promise<ldapRes>(function(resolve, reject){

      ldap.authenticate(credentials.username, credentials.password,function(err:string,user:any,info:string) {
        resolve({err,user,info});
      });

    });

  }

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

When using html2canvas in Angular, it is not possible to call an expression that does not have a call signature

I'm currently working on integrating the html2canvas library into an Angular 8 project. Despite trying to install the html2canvas types using npm install --save @types/html2canvas, I'm still facing issues with its functionality. Here's how ...

Strategies for resolving a mix of different data types within a single parameter

Here, I am setting up the options params to accept a value that can either be a single string or another object like options?: string[] | IServiceDetail[] | IServiceAccordion[]; However, when attempting to map these objects, an error is encountered: Prope ...

Where is the correct location to import the Firestore `Query` type from within Cloud Functions?

I am struggling to import the Query type from Firebase Firestore in one of my TypeScript files. I have tried looking for it in the firebase-admin package without success, and when I attempted to use @firebase/firestore-types (which is not recommended as ty ...

Create typings for object properties in TypeScript

I am inexperienced with TypeScript and am looking to set up types for my object keys. I have explored a few methods to accomplish this, but I am encountering an issue where an error is not triggered when assigning a value of a different type. For example: ...

Capturing Input Data Dynamically with Angular Forms

Is there a way to retrieve values from an unknown number of input fields in Angular? This is the code I am using to generate the input fields: <form (ngSubmit)="submit()" #custom="ngModel"> <div *ngIf="let elem of arr"> <input ...

What is the process for integrating custom TypeScript declaration files into the final build with rollup.js?

I am working on a project in Typescript where the files are built using rollup.js. Within my project, I have certain declaration files set up and I am curious if it is feasible to include these declaration files in the final built declaration file. Declar ...

Is it possible to import a module that was exported in Node.js using the SystemJS import method?

When working on a Node project, we typically import modules using the require keyword. Is it possible to import the same module in an Angular 2 project using import {} from '', even if the d.ts file is not available? For instance, can I incorpora ...

Navigating through the Angular Upgrade Roadmap: Transitioning from 5.0 to 6

As per the instructions found in this helpful guide, I executed rxjs-5-to-6-migrate -p src/tsconfig.app.json. However, an error is appearing. All previous steps were completed successfully without any issues. Any suggestions on how to resolve this? Please ...

A guide to merging two JSON objects into a single array

Contains two different JSON files - one regarding the English Premier League stats for 2015-16 season and the other for 2016-17. Here is a snippet of the data from each file: { "name": "English Premier League 2015/16", "rounds": [ { "name": ...

What is the procedure for incorporating nameless methods into TypeScript interfaces?

While working on a project involving graph visualization, I came across the following interface within the d3.js typings (original source can be found here): export interface Force<NodeDatum extends SimulationNodeDatum, LinkDatum extends SimulationLink ...

`The process of converting Typescript to ES5 through compiling/transpiling is encountering issues`

My current project involves using Webpack and integrating angular2 into the mix. To achieve this, I made adjustments to my setup in order to compile TypeScript. Following a resource I found here, my plan was to first compile TypeScript to ES6 and then tra ...

Unusual Interactions between Angular and X3D Technologies

There is an unusual behavior in the x3d element inserted into an Angular (version 4) component that I have observed. The structure of my Angular project is as follows: x3d_and_angular/ app/ home/ home.component.css hom ...

Leveraging existing providers in Angular 2

What are the possible uses for the useExisting provider? Is it more akin to useExistingOrThrowIfThereIsNone or useExistingOrCreateIfThereIsNone? Is there a way to intentionally choose between these behaviors depending on our specific requirements? If one ...

How can you retrieve the property value from an object stored in a Set?

Consider this scenario: SomeItem represents the model for an object (which could be modeled as an interface in Typescript or as an imaginary item with the form of SomeItem in untyped land). Let's say we have a Set: mySet = new Set([{item: SomeItem, s ...

Discover the versatility of TypeScript by dynamically adding methods to a class!

Are there any examples of dynamically extending a class with a method in TypeScript? I attempted the following: UsersBlocksMyOrders.prototype.myFunc = function():any{ alert('23434'); }; However, the compiler is giving me an error. ...

Tips for managing a dblclick event on a row with data in a kendo-grid while using Angular2

Currently I am working with Angular2 and TS using kendo-grid. It allows me to access the data of the clicked row, but only for a singleClick event like so: (cellClick)="onCellClick($event.dataItem)". However, there is no direct way to achieve this for a d ...

In Angular Google Maps, here's a step-by-step guide on how to zoom in

I am currently utilizing agm/core to showcase the coordinates of a map. Here is the code snippet I am using: <agm-map [latitude]="10.3207886" [longitude]="123.90250049999997"> <agm-marker [latitude]="10.3207886 [longitude]="123.90250049999997 ...

Implement Angular and RxJS functions sequentially

this.functionalityClient.activateFeature(featureName) .pipe( concatMap( feature => { this.feature = feature; return this.functionalityClient.setStatus(this.feature.id, 'activated'); } ), con ...

Creating a stream of observables in RxJs and subscribing to only the latest one after a delay: A comprehensive guide

I am trying to create a stream of Observables with delay and only subscribe to the last one after a specified time. I have three HostListeners in which I want to use to achieve this. I would like to avoid using Observable form event and instead rely on H ...

Disadvantages of utilizing subjects as observables

Do you ever question the necessity of using the "asObserveable()" method on a subject? In my opinion, it seems to result in significant unnecessary overhead. The restrictions on methods like "next()" or "complete()" appear pointless to me. Is there a com ...