【发布时间】: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));
})
})
谢谢。
【问题讨论】:
-
请发布您是如何定义函数的。
-
@FranciscoMateo 完成
-
你没有,你
then()Promise它返回。
标签: node.js express google-vision