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
Advertisement
Answer
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 });