Home > Software design >  function breaks if id doesn't come
function breaks if id doesn't come

Time:09-27

Error : Cannot read property id of undefined

How can I re-write this function so that it doesn't break foundApplication[0].id, if id doesn't come or foundApplication array comes empty?

I cannot alter getDocument function

  async function getApplicationByCbaxUid(cbaxUid) {
    let foundApplication = await dbService.application
      .find({ userID: cbaxUid });
    return getDocument(foundApplication[0].id);
  }

CodePudding user response:

You can validate if the array and the id exist. if you're using latest version of ES, you can use optional chaining (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining):

  async function getApplicationByCbaxUid(cbaxUid) {
    let foundApplication = await dbService.application
      .find({ userID: cbaxUid });
    return getDocument(foundApplication?.[0]?.id);
  }

if you don't

  async function getApplicationByCbaxUid(cbaxUid) {
    let foundApplication = await dbService.application
      .find({ userID: cbaxUid });
    return foundApplication.length && foundApplication[0].id && getDocument(foundApplication[0].id);
  }

This is doing all the normal validations which the latest operator (optional chaining is doing)

CodePudding user response:

You can just add a check if the array is empty

return foundApplication.length ? getDocument(foundApplication[0].id) : null;

CodePudding user response:

set an if statement and add whatever you need to do if it fails to the else block

async function getApplicationByCbaxUid(cbaxUid) {
let foundApplication = await dbService.application
  .find({ userID: cbaxUid });
if(foundApplication.length){
  return getDocument(foundApplication[0].id)
}else{
   ...do what you want here
}

}

  • Related