首页 > 解决方案 > 等待 node.js/express 中的 Google Vision OCR 承诺并返回

问题描述

我无法从 Google Vision OCR 返回承诺。以下是来自 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);
      });

这会将全文输出到控制台。如果我将上面的代码放入一个函数并返回变量检测,我只会得到未定义的返回。我认为问题的原因是承诺是异步的。

如何在路由中返回检测并等待承诺解决,以便我可以通过 res.send 返回它?

这是功能:

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;
    });
}

这是路线:

app.post('/getmytext', function (req, res) {
  var upload = multer({
    storage: storage
  }).single('userFile')
  upload(req, res, function (err) {
    res.end(ocrresults(imagepath));
  })
})

谢谢你。

标签: node.jsexpressgoogle-vision

解决方案


您可以创建一个单独的模块:

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;

并在您的路线中导入并使用:

 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));
      })
  })
})

推荐阅读