Save the date! Join us on October 16 for our Product Ops launch event. Register here.
Oct 31, 2022 02:43 PM
I’m certain this is a lack of understanding of JS or synchronous/asynchronous operations on my part, but: if I want to call Airtable.base.create
through the Node.js module and actually get the created records (or error) returned to be used elsewhere, how would I do that?
Currently, my code looks like this:
export async function createRecord(record) {
base('example').create({
"field": record["field"]
}, function(err, record) {
if (err) {
console.error(err);
return;
}
console.log(record.getId());
});
}
I can get the information logged to console just fine, but I’m not clear on how to properly return it or assign it to a variable and use it elsewhere.
Solved! Go to Solution.
Nov 01, 2022 12:52 PM
So I asked elsewhere and it seems the real problem was the asynchronicity, not the variable scope. Having a variable above the function would still just give me an array of unresolved Promise objects.
The solution I wound up with looks like this:
export async function createRecord(record) {
return new Promise((resolve, reject) => {base('example').create({
"field": record["field"]
}, (err, record) => {if (err) reject(err); resolve(record);}); }
)
}
Nov 01, 2022 02:04 AM
Hi @Vital_Cell, how about you declare a variable above your function and store record ids there? As you’re passing the record anyways, you could declare an empty array and push record ids (or the entire record) into that array.
Then you’re able to reference those later on. Code could looks like this:
const records = [];
async function createRecord(record) {
...
records.push(record)
}
Nov 01, 2022 12:52 PM
So I asked elsewhere and it seems the real problem was the asynchronicity, not the variable scope. Having a variable above the function would still just give me an array of unresolved Promise objects.
The solution I wound up with looks like this:
export async function createRecord(record) {
return new Promise((resolve, reject) => {base('example').create({
"field": record["field"]
}, (err, record) => {if (err) reject(err); resolve(record);}); }
)
}