我试图在 Typescript 中执行命令链操作(我对 TS 不太熟悉)并且我在执行代码时遇到问题。基本上第二个命令首先执行。我希望第二个等待第一个。
这是我的 Orchestrator 类:
export class Orchestrator {
private commands: Command[] = [];
withCommand(cmd: Command): this {
this.commands.push(cmd);
return this;
}
async run(): Promise<void> {
for (const cmd of this.commands) {
try {
await cmd.execute();
} catch (error) {
throw error;
}
}
}
}
这是索引:
import { Orchestrator } from "./orchestrator";
export class Main {
private orchestrator: Orchestrator;
constructor() {
this.orchestrator = new Orchestrator();
}
async run() {
try {
await this.orchestrator
.withCommand(new FirstCommand())
.withCommand(new SecondCommand())
.run();
} catch (error) {
console.error(`Orchestration failed: ${error}`);
process.exit(1);
}
}
}
对于第一个和第二个命令,我有这个代码:
export class FirstCommand implements Command {
async execute(): Promise<void> {
const scriptPath = join(__dirname, "myscript.sh");
const bashRunner: BashRunner = new BashRunner();
await bashRunner.run(scriptPath);
}
}
谢谢
固定...
BashRunner
是问题所在。我使用 resolve() 的方式有问题。
现在代码可以工作了,看起来像:
import { spawn } from "child_process";
export class BashRunner {
async run(filepath: string): Promise<void> {
const child = spawn("bash", [filepath]);
return new Promise<void>((resolve, reject) => {
child.stdout.on("data", (data) => {
console.log(`stdout: ${data}`);
});
child.stderr.on("data", (data) => {
console.log(`stderr: ${data}`);
});
child.on("exit", (code) => {
if (code === 0) {
resolve();
} else {
reject(new Error(`Export script exited with code ${code}`));
}
});
});
}
}
谢谢@konrad