Home > Enterprise >  How to handle a mysql query when it returns null on await?
How to handle a mysql query when it returns null on await?

Time:10-29

I have an async function with multiple mysql queries like this:

const memberdata = async function() {
 somequery1 = await doquery('id','table1','member_id',userid);
 somequery2 = await doquery('id','table2','member_id',userid);
 somequery3 = await doquery('id','table3','member_id',userid);
 problem = await doquery('id','sessions','member_id',userid);

 const array = {somequery1 : somequery1[0].id, somequery2 : somequery2[0].id, somequery3 : somequery3[0].id, problem : problem[0].id};
 return (array);
   };
   
   memberdata().then(v => {  
    username = v.somequery1;
    sex      = v.somequery2;
    age      = v.somequery3;
    session  = v.problem
});

Most of the queries are expected to return a value because there is always at least one record on their tables. The only exception is problem where 50% of the time no record will be found thus upon declaring session I will get an error saying UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch().

That wouldnt be a problem if that was the only query but thats not the case so what can I do to have problem simply return 0 or null in case no record is found?

Thank you.

CodePudding user response:

I think you just need to learn how if statements work.

My guess is that doQuery returns 0 or more records, and your code misbehaves if it's 0, because you are referring to:

problem[0].id

If the array has 0 elements, this triggers your error.

So the solution is to add an if statement that handles this case:

if (problem.length === 0) {
  // Do something
} else {
  // Do the normal thing
}

CodePudding user response:

If the doquery always returns a Promise that resolves to an array, you need to check that the array is populated before accessing properties of the [0]th element.

When returning, change

problem : problem[0].id};

to

problem : problem.length ? problem[0].id : 0};

You also might consider using Promise.all to make the code run in parallel.

  • Related