发出与对象属性相等的设置回调结果(node-tesseract)

时间:2018-08-14 18:22:49

标签: javascript node.js object callback tesseract

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

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中手动进行操作,这也很好

1 个答案:

答案 0 :(得分:1)

您将必须更改代码,以便readScreenshot方法允许您返回承诺对象。

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