OH3 - Javascript within rule: early return

Hi everybody,

is there a possibility to have an early return within a JavaScript Script in a rule?
Something like:

This throws me the following error:

2020-12-29 22:36:09.617 [ERROR] [internal.handler.ScriptActionHandler] - Script execution of rule with UID '7a9d6a5b50' failed: <eval>:6:1 Invalid return statement

 return; 

 ^ in <eval> at line number 6 at column number 1

exit works, but it will only exit from the if clause but not from the whole rule.

1 Like

Did you get a solution yourself?
I have checked the script files in openhab-core github repo, but didn’t find something useable.

I have replaced the return statements in my rules with else clauses for now,
since i only had used it in some small rules.

You can define a function and call it, similar to the JS transform, like:

(function() {
  if (...) return;
})();
1 Like

Thanks for your replies. So far I’m using if clauses. Isn’t a big problem since nobody else needs to understand the logic in my rules and they are not too complex :wink:

Nothing new about that? My rules are getting longer and longer without

return;

:thinking:

Same here…

Push :wink:

One more vote for this, as DSL rules have it :pray:
Rules DSL early-returns

Would case statements in JavaScript work?

switch(rfinput) {
  case '53D80A':
    var TOPIC = "jedwood/raw/frontdoor-sensor";
var PAYLOAD = "ON";
//  events.postUpdate('Doorfront_Doorfront', 'OPEN');
  logger.info('Front door opened');
    break;
```javascript
your code goes here

Nice thinking but the break; in the switch() function will just break out of the switch() function.
If there is code after the switch() then it still gets executed.
It could work if there was nothing after the switch() but the break is not ending the script proper.

example below, the last line get executed no matter what the result of the switch() is

switch (cmd) {
  case "UP": finalcmd = 'm000;'
    break;
  case "DOWN": finalcmd = 'm100;'
    break;
  case "STOP": finalcmd = 's;'
    break;
  default: finalcmd = 'm' + "000".substring(0, 3 - cmd.length) + cmd + ';'
}

cmdtosend = "!" + ba + finalcmd;     <----- This  gets executed  no matter what.

I guess a script is just a code block, that gets run (evaluated) by the scripting engine. The return statement is only valid in functions and this might be the reason, that you cannot use return in the script.

But you can always wrap your code into a function. I do it like that:

function main() {
  // Write your code here
  
  // Return early from the function, if necessary 
  return;
}

// Call your main function from the sript
main();
1 Like