What I am trying to do: Pull data from airtable and put it into an array so that the items within this array can be mapped to an html table later on.
The issue I am having: Javascript pulls data from airtable in an asynchronous way (or so I understand it as such) so no matter if I use an async await function or just a normal one I am always getting a promise returned. All I want to do is to pull these items from the table and put them in an array but it is proving to be more difficult than it should be. (Still new to javascript, so it could just be that I am not understanding everything fully yet).
Code to pull the data:
var Airtable = require('airtable');
var base = new Airtable({apiKey: 'API-KEY'}).base('BASE-ID');
const table = base('BASE-NAME');
let lst = [];
const getRecords = async () => {
try {
const records = await table.select().all();
for(i = 0; i < records.length; i++){
lst.push(records[i])
}
} catch (err) {
console.error(err);
}
}
I know the above code works because if I switch out the line where I am pushing the data to the lst with a console.log(records[i]) I get the correct data item am trying to push to the lst printed to the console. The issue arises when I try to run a console.log(lst). It just returns Promise {pending}.
So, what I happened to come across in the developer doc and here on stack overflow is that I need to use a .then() in order to return the lst so, I tried the following:
getRecords().then(res => {
console.log(lst)
}
);
which did indeed give me the desired results I was looking for but now if a run a console.log(lst) I get the same Promise {pending} message printed to the console.
Does this mean I will have to map the items within lst to the HTML table within the
getRecords().then(res => {
console.log(lst) // so instead of printing the lst to the console here, would I just map the items to the html table?
}
);
section of the code?