I have a async function which makes a face_detection
command line call. It's working fine otherwise, but I can't make it to wait for the response. Here is my function:
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
in my response I return is always undefined
because the response is sent to client before the response from face_detection
is ready. How could I make this work?
You can either use the child_process.execSync
call, which will wait for the exec to finish. But executing sync calls is discouraged ...
Or you can wrap child_process.exec
with a promise
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);
}
});
});