2

I need to read multiple files into a single function A. I need to use FileAPI for it. But FileReader performs an asynchronous download. Can I get the contents of all files at the end of function A without exiting, or not?

1 Answer 1

1

Just to be perfectly clear, FileReader isn't downloading anything. It is asynchronously reading the File contents (as it appears on disk) into memory.

To do what you want, just keep track of the read files and call a callback when they're all done:

document.querySelector('[type="file"]').change = function(e) {
  handleFiles(toArray(e.target.files), function(results) {
    // results is an Array containing the FileReader results.
    alert('Done!');
  });

function toArray(list) {
  return Array.prototype.slice.call(list || [], 0);
}

function handleFiles(files, callback) {
  var results = [];

  files.forEach(function(file, i) {
    var reader = new FileReader();

    // Closure to capture the file information.
    reader.onload = function(e) {
      results.push(e.target.result);
      if (results.length == files.length) {
        callback(results);
      }
    };
    reader.readAsDataURL(file);
  });
}

Try it: http://jsbin.com/epatel/3/edit#html,live

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.