Return data from inside onloadend event

Viewed 18

plotDual is supposed to receive the formatted data that the getData function receives from the filereader. I have realized that my problem is that the onloadend method is asynchronous and thus the return statement in the getData functions are empty but am not sure how to fix it. The getData functions are definitely formatting correctly as I have 2 other functions in my code that plot the long and short separately and that works fine.

the function that takes the data and turns it into a plot

function plotDual(){
  short = getDataDualShort();
  long = getDataDualLong();

  var trace1 = {
    x: short[0],
    y: short[1],
    type: 'scatter'
  }

  var trace2 = {
    x: long[0],
    y: long[1],
    type: 'scatter'
  }


  var layout = {
    xaxis: {
      type: 'log',
      title: 'Time[s]'
    },
    yaxis: {
      title: 'Current Density [A/m^2]',
      rangemode: 'tozero'
    }
  };

  data = [trace1, trace2]
  Plotly.newPlot('dualPlot', data, layout);
}

the function to get the long data (short data function is formatted the same), the return statement is returning nothing since it isn't waiting for the onload to finish


function getDataDualLong() {
  const fr = new FileReader();
  fr.onloadend=e=>{
    let r = fr.result.split("\n").
    map(e=>{
      return e.split(",")
    });
    var gateWidth = document.querySelector('#gateWidthDual').value;
    var numFingers = document.querySelector('#numFingersDual').value;
    var zeroPoint = document.querySelector('#zeroPointDualLong').value;
    var newtable = TableCsv.formatArrLongTime(r,gateWidth,numFingers)

    //placing values in arr for second chart
    var start = TableCsv.getSecondFive(newtable,2)-2;
    if (zeroPoint!=""){
      start = (Number(document.querySelector('#zeroPointDualLong').value) * 2)-1;
    } else {
      document.querySelector('#zeroPointDualLong').value = (start/2 + 0.5).toString();
    }
    var time = 0;
    timeValues = [];
    JDValues = [];
    newtable = newtable.slice(start);
    for(var i = 1; i<newtable.length; i++){
      timeValues.push(time);
      JDValues.push(TableCsv.regex("'" + newtable[i][3] + "'"));
      time += 500000;
    }

  }
  fr.readAsText(document.querySelector("#csvFileInputDualLong").files[0]);
  return [timeValues,JDValues]
}

any help is appreciated, thank you

0 Answers
Related