简体   繁体   English

从Node中阻止Javascript函数访问值

[英]Accessing values from blocking Javascript functions in Node

The below function, startScript , contains blocking code that takes some time to run. 下面的函数startScript包含阻塞代码,需要一些时间才能运行。 In my setInterval loop, I want to access the weight value that it returns. 在我的setInterval循环中,我想访问它返回的weight值。 However, when I run this Node program I receive an error saying that new_weight is undefined. 但是,当我运行此Node程序时,收到一条错误消息, new_weight未定义new_weight

I tried running startScript.on('close', ...) within the loop, but this throws an error saying that there is no method on for startScript 我尝试在循环中运行startScript.on('close', ...) ,但这引发了一个错误,指出startScript on没有方法

What am I doing wrong here? 我在这里做错了什么?

var spawn = require('child_process').spawn
var path = require('path');
var split = require('split');
var pythonData = [];
var weight = null;

function startScript(){
  var pyScript = spawn('python', [ path.join(__dirname, 'script.py') ]);
  pyScript.stdout.on('data', function(lineChunk){
    pythonData = lineChunk.toString().replace(/[\S|\n|\[|\]]/,"").split(',');
  });

  pyScript.on('close', function(code){
    var sum = 0;
    for(var i=0; i < pythonData.length; i++){
      sum += parseFloat(pythonData[i]);
    }
    var weight = sum / pythonData.length;
    console.log("weight: " + weight);
    return weight;
  });
}

setInterval(function(){
  if (some event that occurs infrequently){
    startScript();
    var new_weight = weight + 100
    console.log(new_weight);
  }
}, 1000);

You cant' return from pyScript.on() , it's asynchronous. 您无法从pyScript.on()返回,它是异步的。 The parent function has returned already long before the other return happens. 父函数已经很久才返回另一个返回。 Instead, you must use callbacks. 相反,您必须使用回调。

function startScript(callback){ // ******
  var pyScript = spawn('python', [ path.join(__dirname, 'script.py') ]);
  pyScript.stdout.on('data', function(lineChunk){
    pythonData = lineChunk.toString().replace(/[\S|\n|\[|\]]/,"").split(',');
  });

  pyScript.on('close', function(code){
    var sum = 0;
    for(var i=0; i < pythonData.length; i++){
      sum += parseFloat(pythonData[i]);
    }
    var weight = sum / pythonData.length;
    console.log("weight: " + weight);
    //return weight; // you can't return weight. Instead, execute the callback.
    callback(weight); // ******
  });
}

setInterval(function(){
  if (some event that occurs infrequently){
    startScript(function(weight){ // ******
      var new_weight = weight + 100
      console.log(new_weight);
    }); // ******
  }
}, 1000);

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

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