What should be done when a MySQL query returns null during an await process?

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?

Answer №1

Ensure that if the doquery consistently returns a Promise resolving to an array, you validate that the array is not empty before accessing properties of the first element within it.

When making a return, adjust

problem : problem[0].id};

to

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

You might also want to explore using Promise.all for concurrent execution of the code.

Answer №2

Understanding the functionality of if statements is crucial for your code to run smoothly.

It appears that when doQuery doesn't return any records, your program encounters issues because it tries to access:

problem[0].id

This error occurs when the array is empty.

To resolve this issue, you should implement an if statement to handle this scenario:

if (problem.length === 0) {
  // Handle empty array case
} else {
  // Proceed with normal operations
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing D3 to load XML data from a file and implementing scales for a bar chart

I came across a helpful tutorial on d3 that focuses on creating a bar chart using scales. Unfortunately, I encountered an issue while trying to load my data from an XML file. It seems like my problem lies in not properly determining the length of the datas ...

Updating Sencha list itemTpl on the fly

Is there a way to dynamically change the itemTpl in a Sencha list to adjust the visibility of a column based on certain conditions? Your assistance would be greatly appreciated. ...

Failure to establish secure SSL connection with MySQL using PHP PDO

I am currently in the process of creating a PHP application that needs to connect to a MySQL server using SSL. I have successfully connected using mysql_connect, but I am facing issues when trying to do it with PDO. Every time I attempt to connect, I encou ...

Converting Vue HTML to PDF without relying on html2canvas functionality

My current challenge involves creating a PDF file from either HTML or Vue component. I have experimented with various libraries such as jsPDF, html2pdf, and vue-html2pdf, but it seems like they all rely on html2canvas, causing the UI to freeze for a few ...

Having trouble clicking on the corners of fabricjs elements with threejs raycasting

I've been working on recreating this application, and although it's functioning currently, I'm facing an issue with clicking the corner of the text accurately as it always requires an offset. Here is the link to my current progress: https:/ ...

Implementing notifications in React JS

Hey there! I'm new to React JS and I need some guidance on how to add notification with action buttons in my PWA. Is there any specific way to achieve this in React JS? I have been attempting to integrate notifications into my progressive web app usi ...

When attempting to send data from Ajax to PHP as JSON, an error occurs and the data transmission fails

When attempting to send data as JSON, an error response is received stating: SyntaxError: Unexpected token < in JSON at position 0. If the data is sent as text, it successfully reaches PHP, but PHP does not respond accordingly. AJAX/JavaScript using J ...

Typescript error: The property 'set' is not found on type '{}'

Below is the code snippet from my store.tsx file: let store = {}; const globalStore = {}; globalStore.set = (key: string, value: string) => { store = { ...store, [key]: value }; } globalStore.get = (key) => { return store[key]; } export d ...

"Put Jest to the test by running it with the Express

Currently, I am in the process of learning how to build an API with TypeScript and experimenting with testing it using the Jest framework. When utilizing a basic Express application like app = express() supertest(app) everything works smoothly. However, ...

Zebra lines overlooking unseen details

Imagine having a table where rows can be dynamically assigned classes such as .hidden, which hide those rows using CSS. The rows are styled with alternating colors, like this: tr:nth-child(even) { background-color: $light-grey; } But here's the ...

I'm looking to utilize this script to generate multiple buttons that insert content into a textarea. How can

Finally, I stumbled upon a script that enables undo/redo functionality for programmatically inserted text. You can find it here. If you want to check out the original script demo, click here. Here is the initial script: <div class="snippet" data-lang= ...

Leveraging ng-class for selectively applying CSS3 animations based on conditions

When specific conditions are met in my controller, I apply two CSS3 animations to the DOM using ng-class. The animations (shake Y & shake X) are added based on certain criteria being satisfied. Here is a snippet of the relevant JavaScript code: $scope.sub ...

Enhancing the Strength of Password Generator

Example of a Simple Password Generator: function createPassword() { var characters = "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOP" + "1234567890" + "@\#\-!$%^&*()_+|~=`{}\[\]:\";& ...

What is the best way to display my images within Material UI Cards using React with Typescript?

I'm currently faced with a challenge of rendering images within Material UI's cards. I am successfully passing props to each card from a constants.tsx file where the heading, description, and bodyHeader are all properly read, but for some reason, ...

Updating the Keycloak token in VueJS using keycloak-js even when it is still valid

I have implemented a VueJS frontend connected to Keycloak using keycloak-js openid, without using the implicit flow https://i.sstatic.net/BxhJh.png Currently, there is a scenario in which the Backend NodeJS adds groups to a user in Keycloak. However, in ...

JavaScript: Locate the HTML Attribute that Matches an ID

If you want to use just JavaScript, without relying on libraries like JQuery, how can you retrieve the data attribute associated with a specific Id? For example: <div id="id-test" data-qa="data-qa-test"> </div> Input: &quo ...

Designing a multisite manager application: Best practices and tips

Currently, I am in the process of developing a web application that will be responsible for managing numerous websites. I am faced with the decision of choosing between Node.js and Laravel (PHP) as the platform to build this app upon. My main goal is to en ...

Using the "and" operator in REGEXP

In my database, I have a table called "content" with the following data: id content 1 a 2 a b c 3 b a 4 c e a I am looking to retrieve all ids where both "a" and "c" are present in the content column. I already know how to find ids wher ...

What do I need to add in order to connect a controller to a form submission?

Let's set the scene: There are multiple newsletter forms scattered across a webpage, all needing to perform the same action. This action involves making an AJAX request with certain data and displaying a message using an alert once the request is comp ...

What could be causing the show() method to malfunction in jQuery?

My attempt at creating a basic slideshow using jQuery involves only 3 images in rotation. To navigate between images, I have utilized the next() method in my code. Here is how it is meant to function: Upon clicking a link (class="next"), a funct ...