Save multiple records to a collection at the same time.

Hi All,

I’m currently having trouble figuring out how to do this. I need to update/insert multiple records into multiple collections.
I am saving those records as lists for their respective collections.
The problem that i’m running into is that i cannot update the collection with the list of records but it seems that i need to loop through each item in the lists updating/inserting them as the loop iterates. However this allows the following update/insert statements to also run at the same time. This shouldnt happen since if there is an error it shouldnt continue trying to update/insert.
Any idea how i can do this?

Current way:
let collectionArray1 = {
// holds multiple objects to be inserted into a collection
}
let collectionArray2 = {
// holds multiple objects to be inserted into a collection
}

for(var i = 0; i < collectionArray1.length; i++){
wixData.update(“Collection1”, collectionArray1[i]); //all of these updates should be done before the following loop starts
}
for(var i = 0; i < collectionArray2.length; i++){
wixData.insert(“Collection2”, collectionArray2[i]); //becasue im looping like this, these inserts will run while the above updates are still running
}

Hi,

it is possible to wait for updates to complete.

You could try this:

const updatePromises = collectionArray1.map( (item) => wixData.insert("Collection1", item) ) // This gives an array of Promise objects

Promise.all(updatePromises) // This gives one promise that will complete, once all update operations are complete
    .then( (insertedItems) => /* Inserts go here */ )

This way, you will start inserts only after all updates have completed.

I hope this helps. Let me know if you need any further assistance.