1
//create a multiple local files selector
<input type="file" id="files" name="files[]" multiple />
document.getElementById('files').addEventListener('change', handleFileSelect, false);


function handleFileSelect(evt) {
    var files = evt.target.files, input, file, fr, url; // FileList object
    input = document.getElementById('files');

//      read in each files selected
    for (var i = 0,f; f = files[i]; i++) {            
        fr = new FileReader();
        fr.onload = receivedText;
        fr.readAsText(f);
     }

//      push each file into windowData array  
    function receivedText(e) {        
        lines = e.target.result;
        newArr = JSON.parse(lines),           
        windowData.push(newArr);

     }

//      check results in windowData

    console.log(windowData);       
    console.log("windowData.length="+windowData.length); 
}

suppose I chosed 2 files, I want the results to be: [file1,file2] and windowData.length = 2 but the results are now: [file1,file2] and windowData.length = 0 !

What is the problem? Why the first console.log get the files in windowData, but the second console.log fail to get the length of windowData? And importantly , how can I use the windowData(which contains 2 files) in the upcoming codes?

Thanks!

P.W
  • 21
  • 7
  • Promisify the onload: `promises.push(new Promise(res => fr.onload = res))`, then you can do `Promise.all(promises)` to get a promise with the results. – Jonas Wilms Apr 15 '18 at 19:47
  • thanks for your answer! I am very new to promise feature, should I replace windowData.push(newArr); with promises.push(new Promise(res => fr.onload = res))? what does res mean specifically here ? :p – P.W Apr 15 '18 at 20:07
  • I think you need some time to read through the duplicate above to understand how Promises work ... – Jonas Wilms Apr 15 '18 at 20:08

0 Answers0