将 FileReader 推送到一个数组中

Pushing FileReader result in an array

我试图在单击按钮时将 FileReader 的结果推送到数组中。当我尝试记录数组时,我可以看到只添加了一个项目,我无法通过 [x] 访问该项目。

我很难将文件内容 (reader.result) 存储在变量中。

$(document).ready(() => {
const inputFile = document.getElementById('input-file');
let games = [];
$('#btn-push').click(() => {
        let file = inputFile.files[0];
        let reader = new FileReader();
        reader.readAsText(file);
        reader.onload = () => {
            games.push(reader.result);
        };

        console.log(games); // Logs array.
        console.log(games[0]); // Logs undefined.
    }
}
<input id="input-file" class="d-none" type="file">
<button id="btn-push">PUSH</button>

<script src="https://code.jquery.com/jquery-3.5.0.js"
        integrity="sha256-r/AaFHrszJtwpe+tHyNi/XCfMxYpbsRg2Uqn0x3s2zc=" crossorigin="anonymous">
        </script>

文件阅读器是 async。这意味着稍后将调用 onload,并且之后的所有代码将在加载事件触发之前执行。

要么您必须将所有逻辑放在 onload 事件中,要么在 load 事件执行后调用一些函数。

另一种方法是通过一系列 promise + async/await:

让您的点击事件也异步

jQuery($ => {
  const inputFile = document.getElementById('input-file')
  const games = []

  $('#btn-push').click(async() => {
    const file = inputFile.files[0]

    // https://developer.mozilla.org/en-US/docs/Web/API/Blob/text#Browser_compatibility
    // const text = await file.text() 

    const text = await new Response(file).text()

    games.push(text)
    console.log(games) // Logs array.
  })
})
<input id="input-file" class="d-none" type="file">
<button id="btn-push">PUSH</button>

<script src="https://code.jquery.com/jquery-3.5.0.js" integrity="sha256-r/AaFHrszJtwpe+tHyNi/XCfMxYpbsRg2Uqn0x3s2zc=" crossorigin="anonymous">
</script>