节点child_process等待结果

问题描述 投票:0回答:3

我有一个异步函数,可以进行

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
的响应准备好之前发送给客户端的。我怎样才能做到这一点?

javascript node.js typescript async-await child-process
3个回答
12
投票

您可以使用

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

或者你可以用承诺来包裹

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); 
        }
      });
});

5
投票

我认为你必须将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';
import * as child from 'child_process';
const exec = util.promisify(child.exec);
const result = await exec(`my command`);

0
投票

一句就能做到这一点:

const execute = async (command: string) => await new Promise(resolve => exec(command, resolve))
const result = await execute(`my command`);
© www.soinside.com 2019 - 2024. All rights reserved.