Search code examples
node.jsasynchronousnode-red

Performing async operation for arrays in a NodeRed function


I'm currently writing a function to parse some incoming JSON data and displaying them as charts. In order to do that, I'm using a for loop and populating JSON data in an array like this.

var allMsg = [];

async.each (jsonData.dataSet,
  function (sensorItem, callback) {
    for each item in array .... {
      var msg1 = {};
      msg1.req = msg.req;
      msg1.res = msg.res;
      msg1.payload = "some payload";
      allMsg.push(msg1);
    }
    callback();
  },
  function(err) {
    node.send([allMsg];
  }
};
return;
}

Above example only send first element which is allMsg[0]. I know that to handle async operations you need to do node.send as opposed to return msg, but I'm just not quite sure where I should do node.send If anyone can help, that'd be super great... Thanks!


Solution

  • In the example given you would need to declare a function to pass as the callback argument to the each

    The other option is to just publish each message as it's created rather than push them to the allMsg array. e.g.

    async.each (jsonData.dataSet,
      function (sensorItem, callback) {
        for each item in array .... {
          var msg1 = {};
          msg1.req = msg.req;
          msg1.res = msg.res;
          msg1.payload = "some payload";
          node.send(msg1);
        }
      },
      function(err) {
        //node.send([allMsg];
      }
    };
    

    But it looks like you are using this function node between a pair of http-in and http-response nodes (msg.res/msg.req). This will not work because the http-response will only reply with the first message it receives, you can not stream multiple messages this way. You could use a join node to wait for all the results to complete if needed.