0

I am new to javascript classes and thought it was going to simplify my life!

The code below is basically making an api call to get a status and repeating it every 2 seconds.

Having moved the code into a class my setTimout callback function is now now recognised as a function. Error: "this.getCommandStatus is not a function"

How do I resolve this issue?

Thanks in advance!

    class CommandInterface {        

    constructor() {

        this.activeCommands = [];
        this.commandStatusUpdateInterval = 2000;
        this.commandStatusUpdateTimer = null;

    }

    async sendCommand(commandData) {

        var postCommandOptions = {
            url: '',
            type: 'POST',
            dataType: 'json',
            data: commandData.command
        };

        postCommandOptions.url = '/api/v1/command/send';

        try {

            var data = await httpService.post(postCommandOptions);

            this.getCommandStatus(data);

        } catch (err) {

            system.log('Chamber _sendCommand: ' + commandData.command.ObjectId + ' ' + commandData.command.CommandName + ' API Failed', err);

        }

    }

    async getCommandStatus(commandStatus) {

        var getCommandStatusOptions = {
            url: '/api/v1/command/status/' + commandStatus.commandCallbackId,
            type: 'GET',
            dataType: 'json'
        };

        try {

            var data = await httpService.get(getCommandStatusOptions);   

                this.commandStatusUpdateTimer = setTimeout(function() {
                    this.getCommandStatus(data);
                  }, this.commandStatusUpdateInterval);


        } catch (err) {

            system.log('command-interface getCommandStatus API Failed [Polling]', err);

        }

    }

}
ee0jmt
  • 335
  • 1
  • 11
  • You resolve this issue by learning how `this` works in JavaScript ;) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this – sjahan Sep 27 '18 at 11:58
  • The documentation for `setTimeout` covers this particular issue, see: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#The_this_problem – Evan Trimboli Sep 27 '18 at 13:52

0 Answers0