Having callback within Node Promises

198 views Asked by At

Using child process I execute a Python script does something a spits data back. I used a Node promise to wait until I get the Python data.

The problem I am facing is there is a callback for an anonymous function, the callback takes two parameters one of which is the python data. Code below explains. How do I call the promise, wait until it resolves then call the callback.

Node Promise

var spawn = require("child_process").spawn;

function sensorData()
{
   return new Promise(function(resolve, reject)
   {
      var pythonProcess = spawn ("python",[pythonV1.py"]);
      pythonProcess.stdout.on("data", function(data)
      {
         resolve(data);
      });
   });

 }

Anonymous Function

...
onReadRequest : function(offest, callback)
{
   #============DOES NOT WORK=========================
   sensorData()
  .then(function(data) 
  {
     callback(this.RESULT_SUCCESS, data);
  })
  #===================================================

   #call promise, wait and then call callback passing the python data
   callback(this.RESULT_SUCCESS, new Buffer(#python data)
}
...

Many thanks

1

There are 1 answers

5
Jeff Breadner On

Unless you know that your pythonProcess will only return one line of data, it's bad practice to call resolve() on every stdout data call. It would be much better to collect data until the process closes, and return it all at once.

I'm also not used to dealing with buffers, so I'm casting stuff to strings here...

var spawn = require("child_process").spawn;

function sensorData()
{
   return new Promise(function(resolve, reject)
   {
      var output = '';
      var pythonProcess = spawn ("python",[pythonV1.py"]);
      pythonProcess.stdout.on("data", function(data)
      {
         output += data.toString();
      });

// Not sure if all of these are necessary
      pythonProcess.on('disconnect', function() 
      {
         resolve(output);
      });

      pythonProcess.on('close', function(code, signal)
      {
         resolve(output);
      });

      pythonProcess.on('exit', function(code, signal)
      {
         resolve(output);
      });
   });

 }


...
onReadRequest : function(offest, callback)
{
   #call promise, wait and then call callback passing the python data
   sensorData()
      .then(function(data) 
      {
         callback(this.RESULT_SUCCESS, data);
      })
      .catch(function(err) 
      {
         // Do something, presumably like:
         callback(this.RESULT_FAILURE, err);
      });
}
...