node.js - 等待 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));
})
})
谢谢你。
解决方案
您可以创建一个单独的模块:
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));
})
})
})
推荐阅读
- javascript - 如何使带有长文本的 div 转到下一行,因为它只是文本溢出?
- node.js - 为什么我在 Nodejs 中收到“SyntaxError: Unexpected identifier”错误
- c# - 反序列化包含键和值关键字的 Json
- android - 如何在 HorizontalScrollView 中添加边距
- python - 如何改进我的功能以提高内存效率?
- java - 从没有 READ 权限的 BLE 客户端读取数据
- javascript - mocha 单元测试 - 如何在每次测试后清除缓存的 javascript
- arrays - 检查结构字符串数组是否包含另一个字符串数组的元素
- laravel - 丢失 Laravel 管理员密码
- python - 如何通过对索引向量的广播进行切片来修改 np 数组?