Save the date! Join us on October 16 for our Product Ops launch event. Register here.
Jun 17, 2019 02:19 PM
I’m using the Airtable API in Wix to create an entry in one of my bases. I can get the entry to create no problem, the issue is I would like to return the entry id after the creation and it returns ‘undefined’. See me code below, I can get the id number to print out at the point shown, but I can’t send it out to my other functions.
I’m pretty new to this, I’m sure it’s just a simple oversight, thank you in advance.
export function getCustomer (){
var nCustomer;
base('Customers').create({
"Name": "John Smith",
"Orders": [
]
}, function (err, record) {
if (err) {
console.error(err);
return;
}
nCustomer = record.getId();
//console.log here I get the record id
});
//console.log here, returns 'undefined'
return nCustomer;
}
Jun 24, 2019 09:36 AM
Basically, return nCustomer
happens BEFORE nCustomer = record.getId()
because javascript is asynchronous. So even though the base().create() method takes time, the rest of the getCustomer() function continues running. So getCustomer returns an undefined variable … then moments later the callback function that defines nCustomer (which was passed as an argument to the create method) is executed—but it’s too late as getCustomer() already finished and returned ‘undefined’.
You’ll want to either:
This article should provide the insight you’re looking for:
Introduction
Reading time: 11 min read
Jun 24, 2019 12:02 PM
Thank you so much! I’ll give that article a read. I did get it to work by calling another function with the record as a variable as you mentioned, but I wasn’t sure if there was something else that was going on.
I’m pretty new to JavaScript so the whole asynchronous thing is getting me caught up.
Thanks again for your help!