节点 child_process 等待结果

Node child_process await result

我有一个异步函数,可以调用 face_detection 命令行。否则它工作正常,但我无法等待响应。这是我的功能:

async uploadedFile(@UploadedFile() file) {
    let isThereFace: boolean;
    const foo: child.ChildProcess = child.exec(
      `face_detection ${file.path}`,
      (error: child.ExecException, stdout: string, stderr: string) => {
        console.log(stdout.length);

        if (stdout.length > 0) {
          isThereFace = true;
        } else {
          isThereFace = false;
        }
        console.log(isThereFace);

        return isThereFace;
      },
    );

    console.log(file);

    const response = {
      filepath: file.path,
      filename: file.filename,
      isFaces: isThereFace,
    };
    console.log(response);

    return response;
  }

isThereFace 在我的响应中,我 return 始终是 undefined,因为响应是在 face_detection 的响应准备好之前发送给客户端的。我怎样才能完成这项工作?

我认为您必须将 child.exec 转换为 Promise 并将其与 await 一起使用。否则异步函数不会等待 child.exec 结果。

为方便起见,您可以使用 Node util.promisify 方法: https://nodejs.org/dist/latest-v8.x/docs/api/util.html#util_util_promisify_original

import util from 'util';
const exec = util.promisify(child.exec);
const result = await exec(`my command`);

您可以使用 child_process.execSync 调用,它将等待 exec 完成。但是不鼓励执行同步调用...

或者你可以用一个 promise

包装 child_process.exec
const result = await new Promise((resolve, reject) => {
   child.exec(
      `face_detection ${file.path}`,
      (error: child.ExecException, stdout: string, stderr: string) => {
        if (error) {
          reject(error);
        } else {
          resolve(stdout); 
        }
      });
});