0

I have a project that is working when using functions but when I convert it into a class it is giving errors when calling the same functions (now methods on the class).

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'getData' of undefined
  at myClass.js:71:35
  at FSReqCallback.oncomplete (fs.js:155:23)

Here is the function added as a method to the class:

class MyClass {

   constructor() {
      
   }

   async myFunction(request, response, next) {

      try {
         
         // get file and write it to disk
         fs.writeFile(file.originalname, file.buffer, async function(err) {

            // error on the next line
            var data = await this.getData();

And it's called like this:

      const {MyClass} = require("./MyClass");
      var myClass = new MyClass();
      myClass.myFunction(request, response, next);

It worked when everything was a function in the same file.

1.21 gigawatts
  • 16,517
  • 32
  • 123
  • 231
  • 1
    I don't see `getTree` anywhere in your code - if that's the part that's throwing the error, it would be helpful to see it. If that's a typo for `getData`, you haven't defined `getData` anywhere, what are you expecting that function to reference? – CertainPerformance Nov 23 '22 at 17:14
  • @CertainPerformance it's a typo. I was just informed that the `this` is no longer pointing to the class because it's in an function. – 1.21 gigawatts Nov 23 '22 at 17:16

0 Answers0