Re: Async Functions inside a Loop

905 1
Showing results for 
Search instead for 
Did you mean: 

@Kasra @Stephen_Suen @Shrey_Banga and any other JavaScript :mage: ‍♂

Is it possible at all to call an async function from inside a loop?

I’m trying to run a script that contains this loop:

tablesToClear.forEach(table => {
  let recordsToDelete = =>;
  let recordsDeleted = await batchAnd('Delete', table, recordsToDelete);

  if (recordsDeleted !== null) {
    totalRecordsDeleted += recordsDeleted;

where batchAnd() is defined as an async function that makes a call to table.deleteRecordsAsync().

I’m getting this error:

SyntaxError: await is only valid in async function
    at new Function (<anonymous>)
    at _callee2$ (blob:
    at tryCatch (blob:
    at Generator.invoke [as _invoke] (blob:
    at Generator.prototype.<computed> [as next] (blob:
    at asyncGeneratorStep (blob:
    at _next (blob:
    at blob:
    at new Promise (<anonymous>)
    at blob:

Here’s a copy of the base I’m testing it in for greater context:

Test - Airtable

Explore the "Test" base on Airtable.

I’m sure there’s something here that I’m not understanding about how async functions work :man_shrugging:t2:

2 Replies 2
6 - Interface Innovator
6 - Interface Innovator

Yeah, you can use a for loop here instead: for (let table of tablesToClear) { ... }.

You can also make the callback async, like tablesToClear.forEach(async table => { ... }) but if you do that, the callback will be called for each table instantly without waiting for the previous batchAnd to finish, which will likely do the wrong thing.


Well, that was simple. Thank you, @Shrey_Banga.