1

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?

2
  • Please show the whole and exact code of your readFile function. It's obviously broken. Probably in the ... parts. Commented Sep 9, 2019 at 22:20
  • "Why is it returning early?" - does it? From your description ("doesn't move on"), it sounds more like it's never resolving the promise. Commented Sep 9, 2019 at 22:21

1 Answer 1

1

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

fileSelected = async (e) => {
   for (const file of files) {
      await readFile(file);
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry, I actually do have async there. Edited.

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.