lr_*_*tim 1 javascript child-process node.js async-await typescript
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;
}
Run Code Online (Sandbox Code Playgroud)
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);
}
});
});
Run Code Online (Sandbox Code Playgroud)