Skip to main content
Solved

Why does this not run in an async function?

  • March 25, 2022
  • 2 replies
  • 23 views

Forum|alt.badge.img+3

I have the following code that runs fine if I put it in the main body of my App but not if I put it in a function. I’m baffled, hoping folks here can enlighten me as to why. When in the main body, it runs through all of the records in the Teams table. When in a function, only the 1st record is updated. The portion I’d like to have in a function is the code inside of the if (allUsers) block. I have other functions that update in loops, what is so special about this one?

let teamsTable = base.getTable("Teams");
let teamsRecords = await teamsTable.selectRecordsAsync({
    sorts: [{field:"active members", direction: 'asc'}],
    fields: ["active members", "Included Players"]
}); 

if (allUsers) {
    console.log("rebalancing");

    let lowestActiveCount = teamsRecords.records[0].getCellValue("active members");
    console.log("Lowest active count: " + lowestActiveCount);
    let included = lowestActiveCount - 5;

    for (let team of teamsRecords.records) {
        console.log("Changing Included to: " + included);
        await teamsTable.updateRecordAsync(team.id, {
            "Included Players": included
        })
    }
}

Best answer by kuovonne

Welcome to the Airtable community!

When you put it in a function, make sure that (1) you declare the function as an async function, and (2) you use the await keyword when you call the function.

2 replies

kuovonne
Forum|alt.badge.img+29
  • Brainy
  • 6009 replies
  • Answer
  • March 26, 2022

Welcome to the Airtable community!

When you put it in a function, make sure that (1) you declare the function as an async function, and (2) you use the await keyword when you call the function.


Forum|alt.badge.img+3
  • Author
  • New Participant
  • 4 replies
  • March 26, 2022

Welcome to the Airtable community!

When you put it in a function, make sure that (1) you declare the function as an async function, and (2) you use the await keyword when you call the function.


Ahhhh I’d missed the “await” on the function call. Thank you!