0

So I have FileList of files and I need to read them all to an array ie. [fileData1, fileData2], so that I can make a request with all the files to my backend. I'm stuck with all the async opertions and am not sure how to wait for things to finish. I need a way to detect when I can make the request to the backend. I also want to make this in a functional way of programming. Sorry if the question is unclear.

files.map((file) => {
        const fr = new FileReader();

        fr.readAsDataURL(file)

        fr.addEventListener('load', (event) => {
            // This is what I need to get to an array
            const fileData = event.target.value.substr(fr.result.indexOf(',') + 1);

        })
    })
//Here I need to make a single post request with all the files in it

1 Answer 1

1

Since you added the functional-programming tag, how about a good old fashioned recursive function:

function read_files(cur_file) {
    if (cur_file < files.length) {
        // read the next file
        const fr = new FileReader();
        fr.readAsDataURL(files[cur_file]);
        fr.addEventListener('load', (event) => {
            // extract the file data from event here
            read_files(cur_file+1);
        }
    }
    else {
        // we've read all the files
        // send the request
    }
}

read_files(0);
Sign up to request clarification or add additional context in comments.

3 Comments

cur_file counter kinda breaks the immutability rule of functional-programming. Aside that, how would one extract the file to outside of the load function, without using global var.
@user2933157 You are right about cur_file, the is not reason for it to be a global var, I changed my code. As for the second question, you could add an array as an argument to read_files and accumulate the data there.
Thanks! I will try this tomorrow when I have a chance to test it.

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.