How would you return the error or records received from a "create" API call?

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.

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) 
}

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);}); }
    )
}

This topic was solved and automatically closed 3 days after the last reply. New replies are no longer allowed.