【发布时间】:2021-01-28 11:32:34
【问题描述】:
我正在重写一个现有的模块,它会产生一个子进程并执行一个命令。
我已经将它重写为一个类,但是当我运行代码时,我收到一个错误,即 Promise 拒绝并且解析未定义。
我假设我错误地将它们传递给 .call 方法,但我没有找到可以传递它们的不同方式。
代码如下:
import logger from './logger.utils';
import { spawn, ChildProcess } from 'child_process';
/**
* This function runs a spawn command and rejects the promise if timed out
* @param cmd - the command to execute
* @param params - the command's parameters
* @param timeoutMs - timeout in milliseconds
* @param taskDescription - a text description of the task for logging
*/
export class SpawnTimeout {
cmd: string;
params: string[];
finished: boolean;
childProcess: ChildProcess;
timeoutMs: number;
timeout: NodeJS.Timeout;
taskDescription: string;
handlers: Object;
constructor(
cmd: string,
params: string[],
timeoutMs: number,
taskDescription: string = 'no description specified'
) {
this.finished = false;
this.childProcess = spawn(cmd, params, {
stdio: [process.stdin, process.stdout, process.stderr],
});
this.timeoutMs = timeoutMs;
this.timeout = null;
this.taskDescription = taskDescription;
this.cmd = cmd;
this.params = params;
}
exec() {
return new Promise((resolve, reject) => {
const handlers = {
resolve,
reject,
};
this.handlers = handlers;
this.childProcess.once('error', this._onError.call(this.handlers));
this.childProcess.once('exit', this._onExit.call(this.handlers));
this.timeout = setTimeout(this._setTimeout, this.timeoutMs);
});
}
_onError(err: Error, handlers) {
clearTimeout(this.timeout);
const message = `spawn [${this.taskDescription}] ${this.cmd}, ${this.params} failed with error ${err}`;
logger.error(message);
handlers.reject(new Error(message));
}
_onExit(code: number, handlers) {
this.finished = true;
clearTimeout(this.timeout);
logger.debug(`spawn [${this.taskDescription}] finished.code ${code}`);
if (code == 0) {
handlers.resolve(true);
}
// case of error, code !== 0
const message = `spawn [${this.taskDescription}] cmd : ${this.cmd} ${this.params}. failed with code ${code}`;
logger.error(message);
handlers.reject(new Error(message));
}
_setTimeout() {
if (!this.finished) {
logger.warn(
`spawn [${this.taskDescription}] - timeout. cmd : ${this.cmd}, ${this.params}`
);
this.childProcess.kill();
}
}
}
在调用handlers.resolve或handlers.reject时产生错误。
请告知我该如何解决这个问题?或者即使这样的实施良好做法。
【问题讨论】:
-
您误用了“呼叫”。它调用具有另一个上下文的函数,而不是像您期望的那样返回包装器。这就是 'bind' 所做的,但它有另一个签名并且不会在这里工作,因为错误参数应该首先出现。应该是
this.childProcess.once('error', err => this._onError(err, this.handlers)) -
@EstusFlask 请发布这个答案,这解决了问题。
标签: node.js child-process spawn