Async Functions inside a Loop

@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:

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

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.

1 Like