[英]Accessing values from blocking Javascript functions in Node
下面的函數startScript
包含阻塞代碼,需要一些時間才能運行。 在我的setInterval
循環中,我想訪問它返回的weight
值。 但是,當我運行此Node程序時,收到一條錯誤消息, new_weight
未定義new_weight
。
我嘗試在循環中運行startScript.on('close', ...)
,但這引發了一個錯誤,指出startScript
on
沒有方法
我在這里做錯了什么?
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);
您無法從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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.