Search code examples
javascriptpromisees6-promise

Async function returns undefined even though values are returned


I have the following two functions one calling the other but the record variable is undefined followed by errors. I can't figure out why the script doesn't wait. It seems to just proceed with the undefined variable.

async function searchRecord(recordID) {
    client.search({
        index: 'records',
        type: 'record',
        body: {
            query: { match: { _id: recordID } }
        }
    }).then(result => {
        return result
    }).catch(error => {
        console.log(error)
        return []
    })
}

function test(jsonRecord) {
    const userID = jsonRecord.users[0]
    searchRecord(jsonRecord.objectID).then(record => {
        if (record.length === 0) {
            record = jsonRecord
        }
    })
}

The error that I get is: UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'length' of undefined


Solution

  • Try updating searchRecord to return:

    async function searchRecord(recordID) {
      return client
        .search({
          index: "records",
          type: "record",
          body: {
            query: {
              match: { _id: recordID },
            },
          },
        })
        .then((result) => {
          return result;
        })
        .catch((error) => {
          console.log(error);
          return [];
        });
    }