简体   繁体   English

在节点承诺中进行回调

[英]Having callback within Node Promises

Using child process I execute a Python script does something a spits data back. 使用子进程,我执行Python脚本会吐出一些数据。 I used a Node promise to wait until I get the Python data. 我使用Node承诺等待直到获得Python数据。

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. 我面临的问题是有一个匿名函数的回调,该回调具有两个参数,其中之一是python数据。 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. 除非您知道pythonProcess将仅返回一行数据,否则在每个stdout数据调用上都调用resolve()是一个不好的做法。 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);
      });
}
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM