-1

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.

thefatman
  • 1
  • 3

1 Answers1

0

You can create a separate module:

const vision = require('@google-cloud/vision');

function exportDetections(fileName) {
    // Creates a client
    const client = new vision.ImageAnnotatorClient();

    // Performs text detection on the local file
    return client
      .textDetection(fileName)
      .then(results => {
        const detections = results[0].fullTextAnnotation.text;
        return detections;
      });
}

module.exports = exportDetections;

And in your route import it and use:

 app.post('/getmytext', function (req, res) {
  var upload = multer({
    storage: storage
  }).single('userFile')
  upload(req, res, function (err) {
    exportDetections(imagePath)
      .then((detections) => {
         res.end(ocrresults(imagepath));
      })
  })
})
Alexandru Olaru
  • 6,842
  • 6
  • 27
  • 53