I have a script that I'm using to update records in my Airtable base, but it seems to be taking longer than expected and sometimes hangs indefinitely. I'm seeking assistance to optimize the script for better performance.
Script Description: The script aims to update records in the "Tasks" table of my Airtable base. Here's what it does:
- It retrieves records from the "Tasks" table, selecting specific fields: "Predecessors", "Tasks", and "Next task".
- It filters the retrieved records to find tasks that don't have any successor tasks (i.e., "Next task" is empty).
- For each of these final tasks, it traverses the chain of predecessors to update a field called "Milestone Name" with the name of the final task.
- It performs updates in batches of 50 records to avoid hitting Airtable API rate limits.
Code:
async function updateChainWithFinalTaskName() {
const table = base.getTable("Tasks");
try {
const query = await table.selectRecordsAsync({
fields: ["Predecessors", "Tasks", "Next task"]
});
const finalTasks = query.records.filter(record => {
const nextTask = record.getCellValue("Next task");
return !nextTask || nextTask.length === 0;
});
for (let finalTask of finalTasks) {
let currentRecordId = finalTask.id;
let finalTaskName = finalTask.getCellValueAsString("Tasks");
let updates = [];
while (currentRecordId) {
const currentRecord = query.getRecord(currentRecordId);
if (!currentRecord) {
console.error('Record not found, ID:', currentRecordId);
break; // Exit if the current record is not found
}
updates.push({
id: currentRecordId,
fields: {"Milestone Name": finalTaskName}
});
const predecessors = currentRecord.getCellValue("Predecessors");
currentRecordId = predecessors && predecessors.length > 0 ? predecessors[0].id : null;
}
// Perform updates in batches
while (updates.length > 0) {
try {
await table.updateRecordsAsync(updates.splice(0, 50));
} catch (error) {
console.error('Error updating records:', error);
break; // Exit the loop on error
}
}
}
} catch (error) {
console.error('Error selecting records:', error);
}
}
// Call the function with await to ensure it waits for the records to be selected
await updateChainWithFinalTaskName().catch(console.error);
I would appreciate any insights or suggestions on how to optimize this script for better performance. Thank you!