Help

Re: Creating entry from Wix returning 'undefined'

1719 0
cancel
Showing results for 
Search instead for 
Did you mean: 
thatRusty
4 - Data Explorer
4 - Data Explorer

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;

}
2 Replies 2

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:

  • run the code you want inside the create() callback
  • call another function with the record variable as a parameter
  • pass a custom callback function to getCustomer and run that with record as a parameter

This article should provide the insight you’re looking for:

fd79b31652a5202c78fdb600cb753f3765cf1faf.png

Getting to know asynchronous JavaScript: Callbacks, Promises and Async/Await...

Introduction

Reading time: 11 min read

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!