[英]How to run two child processes in succession in node JS
I have two processes, one to generate a json file from an audio and the other one to normalize the json file, they are both in a function.我有两个过程,一个是从音频生成 json 文件,另一个是规范化 json 文件,它们都在一个函数中。
Each time i run the function and the first one runs, the second one refuses to run and when the second one runs, the first one refuses to run.每次我运行该功能并且第一个运行时,第二个拒绝运行,当第二个运行时,第一个拒绝运行。
I want to be able to run the second one after the first one.我希望能够在第一个之后运行第二个。
exec(command, (error, stdout, stderr) => {
if (error) {
console.log("Normalize error", error);
return;
}
if(stderr){
console.log(`stderr: ${stderr}`);
return
}
console.log(`stdout: ${stdout}`);
});
The code above is the one that generates the audio file上面的代码是生成音频文件的代码
exec(`python3 py/scale-json.py json/${song.filename}/.json`, (error, stdout, stderr) => {
console.log("I AM EXECUTING", song.filename)
if (error) {
console.log("Python error", error);
}
console.log(`stdout-python: ${stderr}`);
})
While the code above normalizes it.虽然上面的代码对其进行了规范化。
How do i run them one after the other ?我如何一个接一个地运行它们?
I'd promisify the exec()
function and then use promise-based logic to sequence them:我会承诺
exec()
函数,然后使用基于承诺的逻辑对它们进行排序:
const util = require('util');
const exec = util.promisify(require('child_process').exec);
async function run() {
const { stdout: stdout1, stderr: stderr1 } = await exec(command);
// some logic based on stdout1 or stderr1
const { stdout: stdout2, stderr: stderr2 } = await exec(`python3 py/scale-json.py json/${song.filename}/.json`);
// process final results here
return something;
}
// Call it like this:
run().then(result => {
console.log(result);
}).catch(err => {
console.log(err);
});
You can read about how util.promisify()
works with child_process.exec()
here in the doc .您可以在文档中了解
util.promisify()
如何与child_process.exec()
) 一起工作。
have u tried to use the Normalizer as a callback part?您是否尝试过使用 Normalizer 作为回调部分?
exec(`python3 py/scale-json.py json/${song.filename}/.json`, (error, stdout, stderr) => {
console.log("I AM EXECUTING", song.filename)
if (error) {
throw new Error (error);
}
console.log(`stdout-python: ${stderr}`);
// It goes here!
exec(command, (error, stdout, stderr) => {
if (error) {
console.log("Normalize error", error);
return;
}
if(stderr){
console.log(`stderr: ${stderr}`);
reject("error");
return;
}
resolve("complete")
console.log(`stdout: ${stdout}`);
});
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.