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
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...