以下函数startScript
包含需要一些时间才能运行的阻塞代码。在我的setInterval
循环中,我想访问它返回的weight
值。但是,当我运行此Node程序时,我收到一条错误消息,指出new_weight
未定义。
我尝试在循环中运行startScript.on('close', ...)
,但这会引发错误,指出on
没有方法startScript
我在这里做错了什么?
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);
答案 0 :(得分:1)
你不能&#39;从pyScript.on()
返回,它是异步的。父函数在其他返回发生之前已经很久就返回了。相反,您必须使用回调。
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);