Why is this function not awaiting the promise to resolve before moving on?

  Kiến thức lập trình

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(){
   const Response = await axios.post('/api/form', FormBody);
   console.log(Response.data); // This provides metadata I need before sendForm() can post to the server
}

For some reason, when the user clicks to the submit the form, the sendForm() function is not awaiting for the fileUploader() to resolve. It instead skips and posts the form which causes errors.

Why is it not awaiting fileUploader() to finish? I even tried using Promise.all() after pushing all the promises in the function to an array first but it didn’t help.

LEAVE A COMMENT