inertia
inertia

Reputation: 4127

Sequentially loading files in javascript

I know there are other answers that are similar to this question, but I'm in a slightly different situation. Consider this block of code:

fileSelected = (e) => {
   const files = e.target.files;
   _.map(files, file => {
      reader.readAsDataURL(file);
      reader.onprogress = () => {...}
      reader.onerror = () => {...}
      reader.onload = () => {
         const resp = await uploadAttachment(file);
         // do something
      }
   }
}

This is iterating asynchronously when I want it sequentially. I want every new instance of FileReader to finish before moving on to the next file... I know it's not ideal, but I'm maxing out 10 files at a time.

I created a separate function to return a new Promise and used fileSelected function to loop through like so:

readFile = (file) => {
   return new Promise(() => {
      reader.readAsDataURL(file);
      reader.onprogress...
      reader.onerror...
      reader.onload...
      ...
   }
}

fileSelected = async (e) => {
   for (const file of files) {
      await readFile(file);
   }
}

But it goes through the first file fine, but it doesn't move on to the next file. What could be the issue here? Why is it returning early?

Upvotes: 1

Views: 106

Answers (1)

Kousika Ganesan
Kousika Ganesan

Reputation: 609

Use async keyword inorder to use await(If you are not using ES2019)

fileSelected = async (e) => {
   for (const file of files) {
      await readFile(file);
   }
}

Upvotes: 1

Related Questions