0

I'm using the following javascript solution to get the number of pages of a file :

const reader = new FileReader()
reader.readAsBinaryString(file)
reader.onloadend = function () {
 const count = reader.result.match(/\/Type[\s]*\/Page[^s]/g).length
 console.log('Number of Pages:', count)
}

The number of pages is correct in the console but I don't know how to extract that number from the scope of the reader so I can use it elsewhere. I've read How to return the response from an asynchronous call but I don't understand how to implement it for my case

Raikyn
  • 133
  • 3
  • 12
  • you'll need a callback, or a Promise (which is just a fancy callback mechanism) to access that data. The code you've shown isn't enough to help much more than that – Bravo Aug 06 '21 at 08:49

1 Answers1

1

Wrap it in a promise and resolve the value you want:

function getPageNumber() {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsBinaryString(file)
    reader.onloadend = function () {
       const count = reader.result.match(/\/Type[\s]*\/Page[^s]/g).length
       console.log('Number of Pages:', count);
      resolve(count);
    }
  }
}

getPageNumber().then(count => {
  // here, now you have count
});
TKoL
  • 13,158
  • 3
  • 39
  • 73
  • Thanks it works fine when I print count inside the ```.then``` but I can not seem to extract that value outside of this – Raikyn Aug 06 '21 at 09:01
  • 2
    You need to read up on how async functions work and get a good feel for it. The patterns of thought and design you're currently using won't work, you've gotta figure the async nature of JS out. – TKoL Aug 06 '21 at 09:08