0

I'm using tesseract JS to convert an image into text format. The conversion is successful and I'm able to print it out in the console. But I am unable to get this text outside the scope of the function.

I have tried assigning the text to a global variable and then printing it but nothing happens.

(async () => {

tesseract.process('new.png', (err, text) => {
    if(err){return console.log("An error occured: ", err); }
    console.log("Recognized text:",text);
    });

})();

Need to be able to get the value of text outside the function and use it again in another asynchronous call.

Sayyam Kapoor
  • 85
  • 1
  • 12

1 Answers1

0

If you use asynchronous operations, like Promise, callback, async-await you cannot use synchronous flow anymore.

Think it like this, Asynchronous functions are operations that will be completed in future, you want some value out of it then you CANNOT get the value untill the first asynchronous function is completed.

That being said, you CAN use Promises (seem) like synchronous functions if you use aysnc-await, IF you don't want to use Promise chain. So you need to promisify the tesseract.process function:

const utils = require('util');

(async () => {
  const tessProcess = utils.promisify(tesseract.process);
  try {
    const text = await tessProcess('new.png');
    console.log("Recognized text:", text);
  } catch (err) {
    console.log("An error occured: ", err);
  }
})();

EDIT: After checking the code snippet:

const utils = require('util');
(async () => {
  const browser = await puppeteer.launch({headless: false})
  const page = await browser.newPage()
  const tessProcess = utils.promisify(tesseract.process);
  await page.setViewport(viewPort)
  await page.goto('example.com')
  await page.screenshot(options)
  const text = await tessProcess('new.png');
  //YOU CAN USE text HERE/////////////
  await page.$eval('input[id=companyID]', (el, value) => el.value = value, text);//here too

  await browser.close()
})()
Aritra Chakraborty
  • 9,464
  • 3
  • 18
  • 26