Before a form can be submitted to the server, it must await
file uploads to finish and return their metadata. I imagine this is a common scenario for many apps.
The sendForm()
function is this:
async function sendForm(){ // The async function that is uploading files and must be awaited upon await fileUploader(); // The FormBody is all the fields in the form. This should not run until fileUploader() has resolved. axios.post('/api/form', FormBody); }
The fileUploader()
function takes the files and should await each one:async function fileUploader() {
for (let i = 0; i < Form.Files.length; i++) { if (!Array.isArray(Form.Files[i])) { // If item in Form.Files is not an array then skip it. // This is because the first element of the array is the binary file and the second element is metadata continue; } // Only add files to the upload queue if they are not already uploaded or currently being uploaded if (!Form.Files[i][1].IsUploaded && !Form.Files[i][1].IsUploading) { try { Form.Files[i][1].UploadPromise = uploadFile({ File: File, FileIndex: i }); await Form.Files[i][1].UploadPromise; } catch (error) { console.log(`error: ${error}`); } }}
}
The uploadFile()
function is just an axios patch to the server:
async function uploadFile({File, FileIndex}){ FormBody.append("UploadFile", File); const Response = await axios.post('/api/form', FormBody); console.log(Response.data); // This provides metadata I need before sendForm() can post to the server // It adds the metadata to the second element of the array here.// However the function is resolving BEFORE the metadata can be set. Form.Files[FileIndex][1].IsUploading = false; Form.Files[FileIndex][1].IsUploaded = true;}
For some reason, when the user clicks to the submit the form, the sendForm()
it is awaiting the fileUploader()
to make the post to the server but then resolves immediately without setting the metadata. After some time, the metadata is set but by then sendForm()
thinks it has already been resolved so doesn't wait for the metadata to be set.
Why is it not awaiting fileUploader()
to finish completely and set the metadata? I even tried using Promise.all()
after pushing all the promises in the function to an array first but it didn't help.