0

im making a js webpage that takes an uploaded text file and then puts the content of the text file into a variable. From here I can do what I need with the data. My problem is that I cannot get the data into the variable. I can log it to the console, but not into a variable.

unction getFile(inputId) {
  const selectedFile = document.getElementById(inputId).files[0];
  console.log(selectedFile)
  let read = new FileReader()
  read.readAsText(selectedFile)
  let text = ''
  read.onload = function(event) {
    text = event.target.result
    console.log(text)

  }
  text = event.target.result
  console.log(text)
  return text
}

In the code you notice two console.logs. The first one works, but the second does not. It just prints ''

Owen K
  • 11
  • 1
  • I suggest you read https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Introducing – Deadron May 29 '20 at 22:00
  • Thanks for your reply. I have read it before but having trouble where I should put the await. – Owen K May 29 '20 at 23:14
  • if you want to use async/await then use the new [promise version](https://developer.mozilla.org/en-US/docs/Web/API/Blob/text) on the blob and ditch the FileReader, `return await blob.text()` (don't work in IE without polyfill) – Endless May 30 '20 at 15:37

0 Answers0