我正在嘗試根據我的 python 腳本的輸出生成一個新的分數。python 腳本正確回傳資料,JS 程式列印正確,但問題是當我回傳值并列印它時,它顯示未定義
功能代碼 -
async function generateCanadaScore(creditscore = 0) {
console.log(creditscore, "creditscore"); //prints 300
let MexicoData = 0;
const python = spawn("python", [
"cp_production.py",
"sample_dill.pkl",
"mexico",
Number(creditscore),
]);
await python.stdout.on("data", function (data) {
console.log("Pipe data from python script ...");
console.log(data.toString()); //prints number
MexicoData = data.toString();
console.log(MexicoData) // prints number
//working fine till here printing MexicoData Correctly (Output from py file) , problem in return
return MexicoData ;
});
python.stderr.on("data", (data) => {
console.log(data); // this function doesn't run
});
// return MexicoData ; already tried by adding return statement here still same error
}
呼叫函式代碼 -
app.listen(3005, async () => {
console.log("server is started");
//function calling
// Only for testing purpose in listen function
let data = await generateCanadaScore(300);
console.log(data, "data"); // undefined
});
我將無法共享它是機密的 python 代碼。
uj5u.com熱心網友回復:
你不能await在事件處理程式上。(它回傳undefined,所以你基本上在做await Promise.resolve(undefined),它什么也不等待)。
您可能希望使用以下方法包裝您的子行程管理new Promise()(您需要它,因為child_process它是回呼異步 API,并且您需要承諾異步 API):
const {spawn} = require("child_process");
function getChildProcessOutput(program, args = []) {
return new Promise((resolve, reject) => {
let buf = "";
const child = spawn(program, args);
child.stdout.on("data", (data) => {
buf = data;
});
child.on("close", (code) => {
if (code !== 0) {
return reject(`${program} died with ${code}`);
}
resolve(buf);
});
});
}
async function generateCanadaScore(creditscore = 0) {
const output = await getChildProcessOutput("python", [
"cp_production.py",
"sample_dill.pkl",
"mexico",
Number(creditscore),
]);
return output;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/335927.html
標籤:javascript Python 节点.js 功能 产卵
下一篇:函式的使用/回傳
