我需要一个接一个地运行两个shell命令。这些命令包含在函数中:
function myFucn1() {
exec('some command',
(error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
throw error;
}
console.log(`stdout: ${stdout}`);
console.error(`stderr: ${stderr}`);
});
}
和
function myFucn2() {
exec('some command 2',
(error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
throw error;
}
console.log(`stdout: ${stdout}`);
console.error(`stderr: ${stderr}`);
});
}
当我在触发函数上调用它们时:
app.get('/my_end_point', (req, res) => {
try {
myFucn1();
myFucn2();
res.send('Hello World, from express');
} catch (err) {
res.send(err);
}
});
它以随机顺序运行两个命令,并且仅从第二个功能显示输出stdout, stderr
。
这是由于Java回调函数的性质。当结果可用时(例如命令可能完成),将调用Exec函数,并调用{}中的函数。函数立即退出,第二个函数甚至在您的命令完成之前就执行。
[一种可能的解决方案(但是不好)是将对myFucn2()的调用放在myFucn1()的回调中(例如:console.error之后)。
正确的解决方案是使用单独的线程(请参阅“工作线程”)来跟踪myFucn1()的执行,并在完成时执行第二个。
您可以使用execSync代替exec来同步执行命令。