I am having problems to return a promise from the Google Vision OCR. Here is the sample code from Google:
const vision = require('@google-cloud/vision');
// Creates a client
const client = new vision.ImageAnnotatorClient();
/**
* TODO(developer): Uncomment the following line before running the sample.
*/
// const fileName = 'Local image file, e.g. /path/to/image.png';
// Performs text detection on the local file
client
.textDetection(fileName)
.then(results => {
const detections = results[0].fullTextAnnotation.text;
console.log('Text:');
console.log(detections);
})
.catch(err => {
console.error('ERROR:', err);
});
This will output the full text to the console. If I put the above code into a function and return the variable detections I get only undefined back. I assume the cause of the problem is that a promise is async.
How can I return detections in a route and wait for the promise to resolve so that I can return it via res.send?
This is the function:
function ocrresults(imgpath) {
console.debug("OCR recognition started");
client
.textDetection(imgpath)
.then(results => {
const detections = results[0].fullTextAnnotation.text;
console.log(detections);
return detections;
})
.catch(err => {
var MyError = ('ERROR:' err);
console.error('ERROR:', err);
return MyError;
});
}
This is the route:
app.post('/getmytext', function (req, res) {
var upload = multer({
storage: storage
}).single('userFile')
upload(req, res, function (err) {
res.end(ocrresults(imagepath));
})
})
Thank you.