Help

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
cancel
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 = table.records.map(record => record.id);
  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:

ERROR
SyntaxError: await is only valid in async function
    at new Function (<anonymous>)
    at _callee2$ (blob:https://block---falsh-z06h-lq-e-pb--68v3t0m.airtableblocks.com/e9e14464-0db0-424f-ad41-111819081f76:3359:53)
    at tryCatch (blob:https://block---falsh-z06h-lq-e-pb--68v3t0m.airtableblocks.com/e9e14464-0db0-424f-ad41-111819081f76:181:21)
    at Generator.invoke [as _invoke] (blob:https://block---falsh-z06h-lq-e-pb--68v3t0m.airtableblocks.com/e9e14464-0db0-424f-ad41-111819081f76:400:26)
    at Generator.prototype.<computed> [as next] (blob:https://block---falsh-z06h-lq-e-pb--68v3t0m.airtableblocks.com/e9e14464-0db0-424f-ad41-111819081f76:234:25)
    at asyncGeneratorStep (blob:https://block---falsh-z06h-lq-e-pb--68v3t0m.airtableblocks.com/e9e14464-0db0-424f-ad41-111819081f76:6:26)
    at _next (blob:https://block---falsh-z06h-lq-e-pb--68v3t0m.airtableblocks.com/e9e14464-0db0-424f-ad41-111819081f76:28:11)
    at blob:https://block---falsh-z06h-lq-e-pb--68v3t0m.airtableblocks.com/e9e14464-0db0-424f-ad41-111819081f76:35:9
    at new Promise (<anonymous>)
    at blob:https://block---falsh-z06h-lq-e-pb--68v3t0m.airtableblocks.com/e9e14464-0db0-424f-ad41-111819081f76:24:14

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.

Interesting!

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