Backend: code question, some skipped code.

My goal is to refresh and update the collection ‘Soci’ with the imported records from the collection ‘importSoci’.

I work with two array with same names, Soci and importaSoci, mirrors of the two collections.

The ‘tessera’ field identify an unique element, old or new. If ‘tessera’ of the new record is equal to ‘tessera’ field of an old record, the routine utilize ‘update’ method, in despite of, ‘insert’ method to insert a new record.

All works, BUT, after the forEach cycles, I’m not able to run anything else .

Only for example you can see at the end of the routine the:
console.log(" END!!! ");
It doesn’t work, have you any idea ?

Thanks in advance
Mauro

// backend/importaSoci.jsw

import wixData from 'wix-data';
import {stringToDate} from 'public/Cloud/stringToDate.js'

export async function importa() {

let options     = { "suppressAuth": true, "suppressHooks": true };
let importaSoci = new Array();
let Soci        = new Array();

console.log("INIZIO - 0");

// popola l'array 'importaSoci' con la relativa collezione 
 await wixData.query("importSoci", options)
.limit(1000)
.find()
.then( (results) => { importaSoci = results.items })
.catch( (err) => {console.log(err)} );

console.log("INIZIO - 1");

// popola l'array 'Soci' con la relativa collezione
await wixData.query("Soci", options)
.limit(1000)
.find()
.then( (results) => { Soci = results.items } )
.catch( (err) => {console.log(err)} );  

console.log("INIZIO - 2");

// Ruota tutti gli elementi dell'array 'importaSoci'
importaSoci.forEach(i => {
 
 // ruota tutti gli elementi dell'array 'Soci' fino a trovare una corrispondenza
 let cn = false;  // true per ogni elemento di importaSoci che troverà una corrispondeza in Soci
 
    Soci.forEach(n => {
 
 // Se c'è una corrispndenza updatiamo il record aggiornato da 'importaSoci' in 'Soci'
 // La copia andrà a buon fine se si troverà in Soci un campo con lo stesso _id      
 if (i.tessera === n.tessera) {
 // ** Copia l'ID dal vecchio elem trovato in 'Soci' nell'ID del corrispondente in 'importaSoci'
                i._id = n._id;
 // ** trasformiamo la data da stringa così come importata in una data legale
                i.scadenza = stringToDate(i.scadenza);
 // ** Come nel db 'Soci' nel field 'nome' aggiungiamo sia il nome che il cognome 
                i.nome = i.nome + " " + i.cognome;
 // ** una volta riuniti il nome e il cognome, cancelliamo il campo cognome nei campi di importaSoci 
 delete i.cognome;
 delete i._createdDate;
 delete i._updatedDate;
 delete i._owner;
 
 cn=true;
 wixData.update("Soci", i, options)
 .then(()=>{console.log("OK TRUE ")})
 .catch((err) => {return err} );
 
            }
     })
 
 if(cn===false) 
 // Nel caso non abbiamo trovato corrispondenze in Soci per l'elemento i-mo di importaSoci,
 // vuol dire che è un socio nuovo, così usiamo -insert- per creare un nuovo record
    {
        i.scadenza = stringToDate(i.scadenza);
        i.nome = i.nome + " " + i.cognome;
        delete i.cognome;
        delete i._createdDate;
        delete i._updatedDate;
        delete i._owner;
        wixData.insert("Soci", i, options).then(console.log("OK FALSE")).catch((err) => {return err} );
    }
 
})

console.log(" END !!! " );  // THIS DOESN'T WORK !

}

no idea ?

I solved putting forEach cycles in a function and putting this function in .then of the last Promise.
But why this behavior ?

import wixData from 'wix-data';
import {stringToDate} from 'public/Cloud/stringToDate.js'


export async function importa() {

let options = { "suppressAuth": true, "suppressHooks": true };
let importaSoci = new Array();
let Soci = new Array();


console.log("INIZIO - 0");
await wixData.query("importSoci", options)
    .limit(1000)
    .find()
    .then((results) => { importaSoci = results.items })
    .catch((err) => { console.log(err) });


console.log("INIZIO - 1");
await wixData.query("Soci", options)
    .limit(1000)
    .find()
    .then((results) => { 
                        Soci = results.items;
                        aggiorna(importaSoci,Soci);  // **** the forEach function !!***
                        })
    .catch((err) => { console.log(err.message) });

console.log("END    !!!!!");
}


//*********** FUNZIONE FOREACH and DATABASE UPDATE */
function aggiorna(arr1,arr2){

let options = { "suppressAuth": true, "suppressHooks": true };

arr1.forEach(i => {
    let cn = false;
arr2.forEach(n => {

  if (i.tessera === n.tessera) {
  cn = true;
  i._id = n._id;
  wixData.update("Soci", i, options)
  .then(()=>{console.log("OK TRUE ")})
  .catch((err) => {return err.message} );
  }
  })
 if (cn === false)
 {    wixData.insert("Soci", i, options)
     .then(console.log("OK FALSE"))
     .catch((err) => {return err.message} );
 }

});
}