0

I know nowaday it has promise or await async for asynchronous things in javascript. I just trying figure out how callback work and use it for real. I have something like this

// HTML
<input type="file" id="file-to-load" />
<button onClick="handleFile()">SHOW DATA</button>

// JS
function readData(callback) {
  var data;

  var fileToLoad = document.getElementById("file-to-load").files[0];
  var fileReader = new FileReader();
  fileReader.readAsText(fileToLoad, "UTF-8");
  fileReader.onload = function (fileLoadedEvent) {
    data = fileLoadedEvent.target.result;
  }

  callback(data);
}

function showData(data) {
  console.log(data);
}

function handleFile() {
  readData(showData);
}

My purpose is execute function showData() only when function readData() has finished. Using all I learned about callback with the code above, but console give undefined for first button click. It display correct data after second click.
Why was that happen ?

dungmidside
  • 508
  • 7
  • 19

0 Answers0