gpt4 book ai didi

javascript - 问题设置回调结果等于对象属性(node-tesseract)

转载 作者:行者123 更新时间:2023-11-30 20:16:50 25 4
gpt4 key购买 nike

我正在尝试将回调函数的结果用作对象的属性。以下是我尝试使用正在构建的模块的方式:

var Screenshot = require("./Screenshot.js")

const test = async function() {
let screenshot = new Screenshot("./screenshots/Screenshot_20180806093446.jpg")
await screenshot.readScreenshot()
console.log(screenshot.text)
}

test() // logs nothing to console

readScreenshot() 似乎没有完成它的工作。我敢肯定,为了完成这项工作,我缺少了一个更精细的细节。

./Screenshot.js 代码如下:

var tesseract = require("node-tesseract");

module.exports = class Screenshot {
constructor(path) {
this.path = path;
this.readScreenshot = this.readScreenshot.bind(this);
}
readScreenshot() {
tesseract.process(this.path, (err, text) => {
if (err) {
throw err;
} else {
this.text = text.split("\n").filter(el => el.trim() !== "");
}
});
}
};

如果我可以让类 Screenshot 的构造函数正确调用此函数,这样我就不必在 app.js 中手动执行,那也很好

最佳答案

您必须更改代码,以便 readScreenshot 方法允许您返回一个 promise 对象。

readScreenshot() {
return new Promise((resolve, reject) => {
tesseract.process(this.path, (err, text) => {
if (err) {
reject(err);
} else {
resolve(text.split("\n").filter(el => el.trim() !== ""))
}
});
});
}

//

var Screenshot = require("./Screenshot.js")

const test = async function() {
let screenshot = new Screenshot("./screenshots/Screenshot_20180806093446.jpg")
let resp = await screenshot.readScreenshot()
console.log(resp)
}

test() // logs nothing to console

关于javascript - 问题设置回调结果等于对象属性(node-tesseract),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51847636/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com