reader.onload 执行完毕后调用方法

Calling a method once reader.onload is finished executing

我正在尝试在我的 reader.onload 完成获取数据后触发一个方法,以便我可以在我的方法中使用该数据。

正如您在下面的代码片段中看到的那样,我很难做到这一点。无论我在哪里执行 doOnLoad() 方法,我总是得到 undefined.

请帮忙

onFileChange(ev) {
    let workBook = null;
    let jsonData = null;
    const reader = new FileReader();
    const file = ev.target.files[0];
    reader.onload = event => {
      const data = reader.result;
      workBook = XLSX.read(data, { type: 'binary' });
      jsonData = workBook.SheetNames.reduce((initial, name) => {
        const sheet = workBook.Sheets[name];
        initial[name] = XLSX.utils.sheet_to_json(sheet);
        return initial;
      }, {});
      const dataString = JSON.stringify(jsonData);
      // console.log(dataString);
      configFile = dataString;
      //  doOnLoad(configFile);
    };
    reader.readAsBinaryString(file);
    doOnLoad(configFile);
}

  
doOnLoad(config) {
  console.log(config);  // Getting Undefined
}

说明

让我们考虑一个采用文件输入的简单示例。要读取文件,您需要 reader 调用 readAsText() 方法。一旦 reader 加载了文件,它将触发一个加载事件,该事件将由 reader.onload.

处理

因此,为了访问文件内容,您需要在事件处理程序中编写代码,即reader.onload,否则如果您登录fileContent 就在 reader.readAsText() 之后,这行代码将在 之前 执行 reader 甚至 完成加载 文件。

// Callback from a <input type="file" onchange="onChange(event)">

const onChange = (event) => {
  var file = event.target.files[0];
  var reader = new FileReader();

  let fileContent;

  reader.onload = (e) => {
    fileContent = e.target.result;

    // the file's text will be logged here
    console.log(fileContent);
  };

  reader.readAsText(file);
  console.log(fileResult); // undefined as reader didn’t finish loading the file
}

解决方案

doOnLoad(configFile); 移动到 reader.onload 事件处理程序中。

// rest of the code

reader.onload = (event) => {
  // rest of the code
  configFile = dataString;
  doOnLoad(configFile);
};

reader.readAsBinaryString(file);

// rest of the code