【问题标题】:Wait for the Google Vision OCR promise in node.js/express and return it等待 node.js/express 中的 Google Vision OCR 承诺并返回它
【发布时间】:2018-07-31 10:43:28
【问题描述】:

我无法从 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);
      });

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

如何在路由中返回 detections 并等待 promise 解决,以便我可以通过 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.js express google-vision


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-18
    • 1970-01-01
    • 1970-01-01
    • 2018-09-10
    • 1970-01-01
    • 2020-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多