Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

NodeJS setImmediate and private class method

So, first time experimenting with setImmediate. It seems it can’t run private class methods. Is that so? If yes, can someone explain to me why?

Doesn’t work

Private class method as argument to setImmediate. Throws Callback must be a function. Received undefined

class TestPrivate {
    public start(): void {
        setImmediate(this.looper);
    }

    async looper(): Promise<void> {
        console.log(`${new Date().toLocaleString()}`);
        await sleep(500);
        setImmediate(this.looper);
    }
}

const testPrivate: TestPrivate = new TestPrivate();
testPrivate.start();

This does work

Static class method as argument to setImmediate

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class TestStatic {
    public start(): void {
        setImmediate(TestStatic.looper);
    }

    static async looper(): Promise<void> {
        console.log(`${new Date().toLocaleString()}`);
        await sleep(500);
        setImmediate(TestStatic.looper);
    }
}

const testStatic: TestStatic = new TestStatic();
testStatic.start();

>Solution :

If you pass this.looper, then the by the time the function is called, looper will no longer have a correct reference to this, so this breaks on the second iteration.

Solve this by using one of the following:

setImmediate(this.looper.bind(this));
setImmediate(() => this.looper);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading