在Node Promises中进行回调

问题描述 投票:1回答:1

使用子进程我执行Python脚本会做一些吐出数据的东西。我使用Node承诺等到我获得Python数据。

我面临的问题是有一个匿名函数的回调,回调有两个参数,其中一个是python数据。以下代码说明。如何调用promise,等到它解析然后调用回调。

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);
      });
   });

 }

匿名函数

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

非常感谢

node.js bluetooth-lowenergy bleno
1个回答
0
投票

除非你知道你的pythonProcess只返回一行数据,否则在每个stdout数据调用上调用resolve()是不好的做法。在进程关闭之前收集数据会更好,并立即返回所有数据。

我也不习惯处理缓冲区,所以我在这里把东西写成字符串......

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);
      });
}
...
© www.soinside.com 2019 - 2024. All rights reserved.