Loop with promise problem

I’m trying to insert data in a Collection, and show it in a table. The fechaActual is a date that increments 1 month in each iteration.
I have two problems:

  1. the date inserted in all records is always the last date obtained (it should be Jan 3, feb 3, mar 3 and apr 3, but in all records the date is apr 3)

  2. the refresh of the dataset is made before the process has finished, so the data shown in the table is not complete. My solution was to use a setTimeout function, but I supposse there is a better solution.

This is the code:

export async function butProbar_click(event) {
    generarCuotas()
 
    setTimeout(function() {
        $w("#dsTemporalCuotas").refresh()
    }, 2000);
}

export function generarCuotas() {
 let cuotaFinal = 6

 let fechaActual = new Date();
    fechaActual = $w('#datePicker1aCuota').value;
    console.log("fechaActual inicial: " + fechaActual);

 for (var cuotaActual=1; cuotaActual <= cuotaFinal; cuotaActual++) {
        console.log("cuotaActual: " + cuotaActual);
        console.log("fechaActual: " + fechaActual);

 let toInsert = {
 "cuotaNo":      cuotaActual,
 "fechaAbono":   fechaActual
        };
 //console.log("guarda fechaActual: " + fechaActual);
        console.log("toInsert: " );
        console.log(toInsert.cuotaNo);

        wixData.insert("TemporalCuotas", toInsert)

        fechaActual.setMonth(fechaActual.getMonth()+1);
    }
 
}

Thank you for your help!

It’ll be better if instead of inserting many times one after the other, you’ll create an array with all the item you need, and after the loop insert them all together. something like:

}//end of the loop after you created an array of objects
wixData.bulkInsert("TemporalCuotas", toInsertArray)
.then(() => {
$w("#dsTemporalCuotas").refresh();
})

By the way, you can also write something like;

//........
let toInsert = [];
toInsert.length = 6;
toInsert.fill(fechaActual);
toInsert = toInsert.map(e => new Date(e.setMonth(e.getMonth() + 1)));
wixData.bulkInsert("TemporalCuotas", toInsert)
.then(() => {
$w("#dsTemporalCuotas").refresh();
})

@jonatandor35 Thank you! I’ll try