问题描述
我有两个过程,一个是从音频生成一个json文件,另一个是规范化json文件,它们都在一个函数中。
每次我运行该函数时,第一个运行,第二个拒绝运行,而第二个运行时,第一个拒绝运行。
我希望能够运行第一个之后的第二个。
exec(command,(error,stdout,stderr) => {
if (error) {
console.log("normalize error",error);
return;
}
if(stderr){
console.log(`stderr: ${stderr}`);
return
}
console.log(`stdout: ${stdout}`);
});
exec(`python3 py/scale-json.py json/${song.filename}/.json`,stderr) => {
console.log("I AM EXECUTING",song.filename)
if (error) {
console.log("Python error",error);
}
console.log(`stdout-python: ${stderr}`);
})
虽然上面的代码对其进行了规范化。
解决方法
您是否尝试过将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,stderr) => {
if (error) {
console.log("Normalize error",error);
return;
}
if(stderr){
console.log(`stderr: ${stderr}`);
reject("error");
return;
}
resolve("complete")
console.log(`stdout: ${stdout}`);
});
})
,
我会推广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);
});
您可以了解util.promisify()
与child_process.exec()
here in the doc的工作方式。