Why does node.send(msg) work, but cannot return msg as normal?

Bit of a strange one here. I have this block of code below:

if (msg.payload.event == "single") {
  var touchpanelIDclicked = msg.topic.split("/")[2]
  var screenIDclicked = msg.payload.screen
  var tileIDclicked = msg.payload.tile
  var touchpanel_zone_mappings = global.get("home.light.config.touchpanel_zone_mappings")
  var zoneID = ""
  
  Object.keys(touchpanel_zone_mappings).forEach(key => {
      if (touchpanel_zone_mappings[key].touchpanelID == touchpanelIDclicked &&
          parseInt(touchpanel_zone_mappings[key].screenID) == screenIDclicked) {
          zoneID = touchpanel_zone_mappings[key].zoneID
          msg.topic = "home/light/" + zoneID + "/scene"
          msg.payload = tileIDclicked - 1
          node.warn(msg)
          return msg
      }
  })
  
}

It never returns a message, but if I use node.send(msg) instead of return msg;, it does return a message, as it should.

I have included node.warn(msg) to verify the topic/payload of the message, and sure enough it only returns once.

Is there some special reason that return msg; cannot run within a forEach code block?

Because the return inside forEach returns to the forEach like a callback.

Use a regular for loop if you want to return early.

3 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.