【问题标题】:Node child_process await result节点 child_process 等待结果
【发布时间】:2020-10-01 06:22:00
【问题描述】:

我有一个异步函数,可以进行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 在我返回的响应中始终是undefined,因为响应在来自face_detection 的响应准备好之前发送到客户端。我怎样才能做到这一点?

【问题讨论】:

  • 请考虑使用 execSync (nodejs.org/api/…) 来同步执行您的代码。
  • @MoxxiManagarm 在异步环境中执行同步操作是非常不鼓励的,因为它会阻塞整个节点进程...

标签: javascript node.js typescript async-await child-process


【解决方案1】:

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

或者你可以用一个承诺包装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); 
        }
      });
});

【讨论】:

    【解决方案2】:

    我认为您必须将 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`);
    

    【讨论】:

      猜你喜欢
      • 2020-03-10
      • 1970-01-01
      • 2021-02-16
      • 2020-03-07
      • 1970-01-01
      • 2019-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多