0

Here is my problem : I have nested loops for data treatment (this is a simplified version from what I have :

 const dataTreatment = (formData) => {
   for (let i = 0; i < formData.agencies.length; i++) {
     for(const type in formData.formTypes) {
       switch(type) {
         case 'address':
           formData[type].forEach(async (item) => {
             await axios.post('', {});
           }
           break;
         case 'schedules':
           formData[type].forEach(async (item) => {
             await axios.post('', {});
           }
           break;
       }
     }
   }
 }

In another file, I execute this function ahead of others and want it to wait for loops to finished but it executes the following functions.

const submit = async () => {
  await dataTreatment();
  await doSomethingAfter();
}

My problem is it doesn't wait and execute "doSomethingAfter" right after. I think i'm missing something about loops and async functions...

Thank you

1 Answers1

0

In order for the await calls to work, your function needs to be declared as async.

 const dataTreatment = async (formData) => { // note the async word
   for (let i = 0; i < formData.agencies.length; i++) {
     for(const type in formData.formTypes) {
       switch(type) {
         case 'address':
           formData[type].forEach(async (item) => {
             await axios.post('', {});
           }
           break;
         case 'schedules':
           formData[type].forEach(async (item) => {
             await axios.post('', {});
           }
           break;
       }
     }
   }
 }

const submit = async () => {
  await dataTreatment();
  await doSomethingAfter();
}

The same is also true of the doSomethingAfter function and needs to be declared async.

GenericUser
  • 3,003
  • 1
  • 11
  • 17