I have a function that uses asynchronous calls to retrieve data from multiple MySQL queries. Here is an example:
const fetchData = async function() {
query1Result = await executeQuery('id','table1','member_id',userID);
query2Result = await executeQuery('id','table2','member_id',userID);
query3Result = await executeQuery('id','table3','member_id',userID);
sessionResult = await executeQuery('id','sessions','member_id',userID);
const resultArray = {query1Result : query1Result[0].id, query2Result : query2Result[0].id, query3Result : query3Result[0].id, sessionResult : sessionResult[0].id};
return (resultArray);
};
fetchData().then(data => {
username = data.query1Result;
sex = data.query2Result;
age = data.query3Result;
session = data.sessionResult
});
In most cases, the queries are expected to return a value as there is always at least one record in their tables. The exception is with sessionResult
, where no records are found about 50% of the time. This leads to an error message:
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error can occur if an async function does not have a catch block or if a promise rejection is not handled using .catch()
.
If this was the only query, it wouldn't be too much of an issue. However, since there are other queries involved, how can I modify sessionResult
to return null or 0 when no records are found?