Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

291
Vistas
Undefined this in higher order function(nestjs)

I'm trying to implement some basic higher order function which would return a new function with provided function surrounded with try catch block. Something like this:

function wrapLogging(f) {
    return async (...args) => {
        try {
            await f(...args);
        } catch (e) {
           log(e);
    };
  }
}

// dummy example:

const executeAndLog = wrapLogging(executeFunction);
executeAndLog();


// nestjs controller and service example:

 @Post('/create')
   async executeAndLog() {
       const executeAndLog = wrapLogging(this.exampleService.create);
       await executeAndLog();
  }

Now the problem is that I get undefined errors in provided this.exampleService.create. "TypeError: Cannot read properties of undefined..." I do get that the context is missing but don't know how to 'connect' it. Tried googling examples and found similar problem with .call or .apply solutions but it didn't work in this case. Maybe it's because the service method provided is async, or it's something to do with nestjs services and their context?

any help is greatly appreciated! ty

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

To use an approach like this, you need to recognize that the lexical this gets lost when using functions. You can use .bind() to rebind the proper this to the method, so that you can still use this inside the method. The following works in keeping this but allowing you to wrap your methods

app.controller.ts

import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';

function wrapLogging(f: (...args: any[]) => any) {
  console.log('Calling method');
  console.log(f);
  return async (...args) => {
    try {
      return await f(...args);
    } catch (e) {
      console.log(e);
    }
  };
}

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  async getHello(): Promise<string> {
    const method = wrapLogging(this.appService.getHello.bind(this.appService));
    return method();
  }
}

app.service.ts

import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
  private greeting = 'Hello World!';
  getHello(): string {
    console.log('Returning greeting');
    console.log(this);
    return this.greeting;
  }
}

HTTP call

xh :3000
HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 12
Content-Type: text/plain; charset=utf-8
Date: Tue, 08 Mar 2022 16:01:19 GMT
Keep-Alive: timeout=5

Hello World!

logs

Calling method
[Function: bound getHello]
Returning greeting
AppService { greeting: 'Hello World!' }

I would suggest going the route of a decorator and modifying the descriptor.value instead of a separate function, as you'll need to do this bind every time you want to wrap your method, but in the end it's up to you.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda