问题描述
我有一个异步功能,该功能可以进行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
的响应准备好之前,响应已发送给客户端。我该怎么做?
解决方法
您可以使用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);
}
});
});
,
我认为您必须将child.exec转换为Promise并在等待中使用它。否则,异步功能将不等待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`);