Tesseract: end of job

Viewed 29

How to known Tesseract has terminated the job in order to start next function? It's running as an async function but i need to start next function when OCR is done. I tried to start when OCR string is not empty but my next function starts before. Should i use "Promise" option ? If yes, how? Here, Tesseract basic example used:

const { createWorker } = require('tesseract.js');

const worker = createWorker();

(async () => {
 await worker.load();
 await worker.loadLanguage('eng');
 await worker.initialize('eng');
 const { data: { text } } = await 
 worker.recognize('myimage.png');
 console.log(text);
 await worker.terminate();
})();
1 Answers

A (potentially over-)simplified explanation: An async function is a function that will do some work in an asynchronous manner. It will return before this work is actually completed (and the next instruction will be evaluated). Therefore it cannot return the result of this work, but will return the promise of the result.

If you want to wait till the asynchronous work is done, you'll have to await the promise. Only then the actual result will be available. Simple example:

async function doSomething() {
  // This line takes take 2s to continue
  await new Promise((r) => setTimeout(r, 2000))

  console.log('3')
  return 42
}

async function main() {
  console.log('1')
  const promise = doSomething()
  console.log('2')
  console.log('promise:', promise)

  const result = await promise
  console.log('4')
  console.log('result:', result)
}

main()

So, if you want to wait for the result of worker.recognize you use await like in the code you posted. If you want to wrap all that in a function, that function will be async and you have to await it if you want to run them sequentially:

const { createWorker } = require('tesseract.js');

const worker = createWorker();

async function runOcr(filename) {
  const { data: { text } } = await worker.recognize(filename);

  // Now do something with the result:
  console.log(text);
}

async function main() {
  // Setup
  await worker.load();
  await worker.loadLanguage('eng');
  await worker.initialize('eng');

  // Process different files
  await runOcr('myimage.png')
  await runOcr('myimage2.png')

  // Tear down
  await worker.terminate();
}

main()
Related