Upcoming database upgrades. Airtable functionality will be reduced for ~15 minutes at 06:00 UTC on Feb. 4 / 10:00 pm PT on Feb. 3. Learn more here

Async Functions inside a Loop

Topic Labels: Scripting extentions
1439 2
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

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.