Reputation: 117
I want to receive an image from a client, convert it into text and then delete the image once it's converted. I'm using the following code:
app.post('/upload', (req,res)=>{
const myFile = req.files.file;
myFile.mv(`D:/web_projects/react-express-mongodb-template/server/pictures/${myFile.name}`)
let img = `D:/web_projects/react-express-mongodb-template/server/pictures/${myFile.name}`
convert(img);
remove(img)
})
app.listen(5000, () => {
console.log('server is running at port 5000');
})
async function convert(img){
const worker = createWorker();
console.log(worker)
await worker.load();
await worker.loadLanguage('eng');
await worker.initialize('eng');
const { data: { text } } = await worker.recognize(img);
console.log(text);
await worker.terminate();
}
async function remove(path){
try {
fs.unlink(path)
} catch(err) {
console.error(err)
}
}
So in the post method I call the convert function and then remove but remove gets executed first and so convert function results in error. Is there a way to handle this issue?
Upvotes: 1
Views: 1488
Reputation: 350961
As convert
is an async
function, and thus returns a promise, replace:
convert(img);
remove(img)
With:
convert(img).then(() => remove(img));
However, this assumes that all awaited worker
method calls in convert
return promises. If this is not the case, and they run asynchronous code, then actually convert
will not properly await those, and you should first promisify them.
Upvotes: 1