0

This is my function, how can I make it so that openFileBrowse() returns the outcome of the function tsvJSON() inside of the reader.onload?

export function openFileBrowse() {
  var input = document.getElementById("filebutton");
  if (input.files[0].type != "application/vnd.ms-excel"){
    alert("You have uploaded a wrong file type. We require a .csv file not a " + input.files[0].type + " file.");
  } else {
    var reader = new FileReader();
    var aftertext = "";
    reader.onload = function(){
      aftertext = reader.result;
      return tsvJSON(aftertext);
    };
    reader.onloadend = function(){
      console.log("loading finished");
    };
    reader.readAsText(input.files[0]);
  }
}

Thanks in advance!

1 Answers1

1

This is not possible when using asynchronous callbacks. Instead, you should add another argument for a callback function which accepts the data from your onload:

export function openFileBrowse(cb) {
  var input = document.getElementById("filebutton");
  if (input.files[0].type != "application/vnd.ms-excel"){
    alert("You have uploaded a wrong file type. We require a .csv file not a " + input.files[0].type + " file.");
  } else {
    var reader = new FileReader();
    var aftertext = "";
    reader.onload = function(){
      aftertext = reader.result;
      cb(tsvJSON(aftertext));
    };
    reader.onloadend = function(){
      console.log("loading finished");
    };
    reader.readAsText(input.files[0]);
  }
}
awarrier99
  • 3,628
  • 1
  • 12
  • 19
  • I now get the error "Uncaught TypeError: cb is not a function at FileReader.reader.onload" How can I fix this? – Hidde van Esch May 06 '20 at 13:27
  • What are you passing in as the argument to your `openFileBrowse` call? Wherever you call this function, you have to pass in a function as an argument to serve as the callback which is executed once your data is loaded – awarrier99 May 06 '20 at 13:28