Help

Await Error in createRecordAsync

Topic Labels: Extensions
1688 4
cancel
Showing results for 
Search instead for 
Did you mean: 
Jerome_CHABAUD
5 - Automation Enthusiast
5 - Automation Enthusiast

Hi,
I wrote a little script who :
1/ Delete some records of the table tableSuiviFacturation

while (recordToDelete.length > 0) {
        await tableSuiviFacturation.deleteRecordsAsync(recordToDelete.slice(0, 50));
        recordToDelete = recordToDelete.slice(50);
  }

2/ Insert some new recors in this table :

await tableSuiviFacturation.createRecordAsync({
                "Client" : [{id: clientsID[item]}],
                "Période" : Periode,
                "Solde début période" :  montantDernierSolde[item],
                 .........

And I 've a error

SyntaxError: await is only valid in async functions and the top level bodies of modules

If I remove the await, the error disappears but I don’t understand why ?!!

4 Replies 4
Jerome_CHABAUD
5 - Automation Enthusiast
5 - Automation Enthusiast

I found my error.
The code was in a loop :
clientsAvecEvenement.forEach( item => {
I replace this code by
for (let item of clientsAvecEvenement) {

And it works with
await tableSuiviFacturation.createRecordAsync({

Sharing the entire statements in question might have been more helpful to scripting newcomers as explaining this behavior with certainty is otherwise impossible. :slightly_smiling_face:

Also, have you tested scenarios with over 50 deletion candidates? This is also just a theory that I can’t confirm with this little to go on but I don’t think your code does what you think it does due to slice/splice confusion.

Slice creates a new array.
Splice mutates the one whose length you’re checking in your conditional.

Ergo using slice will only ever give you one outcome. You want splice.

The section of code that deletes records looks like it was taken from the documentation. Notice that there are two slices. The first slice takes the first 50 records, without mutating the original array. The second slice removes the first 50 records and reassigns the variable to the new remainder. Note that in this case, the variable could not be declared with const.

Of course, using a single line with splice would also work and is more concise. But this bit of code with slice should be fine.

Great point, oversaw the other one.