Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

290
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!