0

I have a class that does some pretty complicated things. For this example, I've simplified it a ton to the following:

class MyClass {
    constructor(name) {
        this.name = name;
    }
}

MyClass.prototype.sayName = function (cb) {
    return this.getName(cb);
};
MyClass.prototype.getName = function (cb) {
    setTimeout(() => {
        console.log("My name is " + this.name);
        cb();
    }, 1000);
};

Now of course there is no need for async code in this example, but in the actual example there is async code (ex. network requests). I just simplified it to make it easier for this question. Also, this actual class is part of a 3rd party package, so I don't really have any control over it.

Anyways, I have the following code that works perfectly:

const myInstance = new MyClass("Bob");
myInstance.sayName(() => {
    console.log("Done");
});

What I'm trying to do to make it more consistent in my code, is build a wrapper that converts those callbacks into promises:

const myInstance = new MyClass("Bob");
const standard = () => {
    return getPromise(myInstance.sayName);
};
standard();
function getPromise(func) {
    return new Promise(function(resolve, reject) {
        func(function() {
            resolve();
        });
    });
}

Problem is. That code doesn't work. I get the following error:

(node:58910) UnhandledPromiseRejectionWarning: TypeError: this.getName is not a function

It looks like inside of the sayName method in that second example this is referring to the global object, and not the instance of MyClass.

Why doesn't this code work? And why is this something else when I try to use it inside of a wrapper?

Charlie Fish
  • 18,491
  • 19
  • 86
  • 179
  • @Quentin not quite sure how that is a duplicate. `myInstance` is the same in the wrapper as outside the wrapper. And `sayName` doesn't have any inner functions. – Charlie Fish Dec 13 '18 at 17:56
  • 1
    You are passing `myInstance.sayName` as a callback. Inside `sayName` you are using `this`. The value of `this` is not the value you want. Therefore you want to know how to access the correct 'this' inside the callback. Which is what the duplicate question is all about. – Quentin Dec 13 '18 at 17:57

0 Answers0