Async/await not working properly with Airtable API in Node.js

I’m having trouble with async/await when fetching records from Airtable using Node.js. The await keyword doesn’t seem to wait for the promise to complete before moving on.

Here’s my code:

async function fetchRecord(identifier) {
  return await airtableBase("Records")
    .select({
      filterByFormula: `{identifier} = "${identifier}"`,
    })
    .firstPage((error, results) => {
      if (error) {
        console.log(error);
        return {};
      }

      console.log(results[0].fields);
      return results[0].fields;
    });
}
items.map(async (item) => {
      itemInfo = getItemInfo(item);

      result = await fetchRecord(itemInfo.identifier);

      console.log(result);
})

The output I’m getting shows undefined first, then the actual data appears later. It seems like the async function isn’t waiting for the Airtable query to finish. How can I fix this so the data is available when I need it?

The problem is that Airtable’s firstPage() method uses callbacks, not promises. So when you use await, it’s not actually waiting for anything. You need to wrap it in a Promise to make async/await work:

async function fetchRecord(identifier) {
  return new Promise((resolve, reject) => {
    airtableBase("Records")
      .select({
        filterByFormula: `{identifier} = "${identifier}"`
      })
      .firstPage((error, results) => {
        if (error) {
          reject(error);
        } else {
          resolve(results[0]?.fields || {});
        }
      });
  });
}

Now the Promise will resolve when the callback fires, and your await will actually wait for the data before moving on.