Express: using async and await leads to an error when attempting to access "result" before it has been initialized

When using the login function that utilizes ExecuteSQL to validate user existence, an error occurs during file execution related to async await.

ReferenceError: Cannot access 'result' before initialization at /Users/naseefali/Documents/Projects/common_express_api/data/DL.js:100:25 at async login (/Users/naseefali/Documents/Projects/common_express_api/data/DL.js:99:24) SELECT fUserPwd FROM tblUser WHERE fUserID ='ADMIN' { recordsets: [ [ [Object] ] ], recordset: [ { fUserPwd: '006060061500675006630067300667' } ], output: {}, rowsAffected: [ 1 ] }

Code

async function testConnection() {
    try {

        const pool = await getConnection();
        if (pool) {
            const result = await pool.request()
                .query('SELECT * FROM tblUser', function (err, sqlResult) {
                    if (err) {
                        console.log(err);
                    }
                    else {
                        console.log(sqlResult);
                    }
                });
        }
        else console.log(pool);
    } catch (err) {
        console.log(err);
    }
};

async function ExecuteSQL(strSQL) {
    try {
        const pool = await getConnection();
        if (pool) {
            const result = await pool.request()
                .query(strSQL, async function (err, sqlResult) {
                    if (err) {
                        console.log(err);
                    }
                    else {
                        console.log(strSQL);
                        console.log(sqlResult);
                        return sqlResult;
                    }
                });
        }
        else console.log(pool);
    } catch (err) {
        console.log(err);
    }
};


async function login(strUID) {
    const strSQL = `SELECT fUserPwd FROM tblUser WHERE fUserID ='${strUID}'`;
    try {
        const result = await ExecuteSQL(strSQL).then(await function () {
            console.log(result);
        });
    } catch (err) {
        console.log(err);
    }

};

login('ADMIN');

Answer №1

because result is accessed before being assigned due to not returning a value in the 'then' callback

 async function login(strUID) {
    const strSQL = `SELECT fUserPwd FROM tblUser WHERE fUserID ='${strUID}'`;
    try {
        const result = await ExecuteSQL(strSQL).then(await function () {
            console.log(result);
        });
    } catch (err) {
        console.log(err);
    }

 };

try changing it to

 const result = await ExecuteSQL(strSQL).then(function (data) {
  return data
 });
 console.log(result);

or simply

 const result = await ExecuteSQL(strSQL);
 console.log(result);

Answer №2

Here I am showcasing the functionality of ExecuteSQL by returning its output.

I have implemented an async function named ExecuteSQL that handles SQL queries and returns the result.

async function ExecuteSQL(strSQL) {
    try {
        const pool = await getConnection();
        // No need to check for pool validity as any errors will be thrown by getConnection() 
        const result = await pool.request().query(strSQL);
        return result;
    } catch (err) {
        console.log(err);
    }
};

async function login(strUID) {
    const strSQL = `SELECT fUserPwd FROM tblUser WHERE fUserID ='${strUID}'`;
    try {
        const result = await ExecuteSQL(strSQL);
        console.log(result);
        return result;
    } catch (err) {
        console.log(err);
    }

};

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

Using Bootstrap 4 to Filter Cards by Title and Tag

I'm attempting to develop searchable cards using HTML, JavaScript, and Bootstrap 4, but I'm facing issues with my code. My goal is to filter these three cards using a search bar, based on their title (h5.card-title) and tags (a.badge). Below is ...

execute the function once the filereader has completed reading the files

submitTCtoDB(updateTagForm:any){ for(let i=0;i<this.selectedFileList.length;i++){ let file=this.selectedFileList[i]; this.readFile(file, function(selectedFileList) { this.submitTC(updateTagForm,selectedFileList); }); } } } ...

During the execution of my asynchronous javascript, it interrupts the flow of the other function

How can I ensure that a function executes after another one in Vue.js? I've tried various methods like async/await, callback functions, and .then, but none seem to work seamlessly. Any suggestions for a possible solution? auth_util.js: async auth () ...

What is causing the qtip tooltip to show up on buttons with different ids?

I have a requirement to display tooltips only for specific buttons and not for others. I am facing an issue where the tooltip intended for the TAB button is showing up when hovering over other buttons like FOO and BAR as well. Could this be due to them sha ...

Do the variables declared in app.js have scope access to the functions within routes, in the context of Express and node.js?

While working with express js, I came across an interesting situation. In my app.js file, I had declared the following: var mongoose = require ('mongoose'); var db = mongoose.connect('mongodb://localhost/testdb'); Next, in my /mo ...

"Utilizing jQuery Mobile's Pagebeforeshow event with the advanced functionality of longlist

Currently, I am utilizing JQuery mobile version 1.0.1. To set up a page, the following code is utilized: <div data-role="page" id="homecomments"> <div data-role="header"> <h1>Comments</h1> <a href='#home&apo ...

Unable to access property value in React component

Hello everyone! This is my first time posting here, so I hope I'm explaining this correctly. I've been working on a React multi-step form, and I'm trying to figure out how to display a dynamic number of input fields in one of the steps. The ...

bespoke slickgrid dropdown editor

I am currently working on implementing a slickgrid feature where a cell needs to display a dropdown (selectlist) with values fetched from a restful service. These values will vary for each row. The requirement is that the user should be able to select one ...

How can you transfer a function to another function within the render return statement?

I am encountering an issue when attempting to pass a function to another function. The initial function successfully downloads JSON data and returns it. However, the subsequent function, which is meant to convert the JSON data to HTML code, is not functio ...

Making a $.ajax post request with complex JSON that meets CORS compliance

I've been searching on various platforms, including stackoverflow, but I haven't been able to find a solution to my specific issue with CORS. I'm trying to send a complex JSON object (with multiple hierarchies) to a CORS server. I've st ...

Setting up GameClosure on a Windows machine

Is it possible to install GameClosure on Windows? The installation guide mentions that only OSX is officially supported, but there have been reports of success running it on Linux and Windows. However, the process for doing this is not well-documented. A ...

Guide on incorporating factories with Ionic/Angular JS while utilizing phonegap

I've been experimenting with global variables in my ionic/angular + phonegap app project by implementing a factory service. However, even adding a simple factory service like the one below somehow disrupts the app and causes all screens to turn compl ...

The PHP post method is unable to retrieve the value of a button tag

In my code file login.php, I have the script to validate if the user exists or not, as well as an AJAX call. Inside the form, there is a button tag; When I set type='submit', the PHP works but the AJAX does not; and when I use type='button&a ...

Is there a way to showcase the contents of the angular "tags" object seamlessly?

Is there a way to show the content of the "tags" object using angular? I attempted to achieve it using {{gallery.tags.tag}} but unfortunately, it did not work import {IPhoto} from "./iphoto"; export interface IGallery { galleryId: string; title: ...

The presence of multiple renderings occurring due to Google Maps InfoBox and an AJAX call

I'm encountering a problem with my implementation of the InfoBox and I'm looking for insights on potential solutions. Currently, I have around 1000 client-side markers that are dynamically added to the page. They are created using the following ...

Mastering the complexities of Javascript, AJAX, and PHP intertwined

Hello everyone, I'm currently working on a website in Codeigniter and I have a form that I submit using PHP, which works perfectly. However, I also have a small dropdown menu on the side of my page that allows users to jump between pages by clicking o ...

Creating a full-screen loading animation that appears when a button is clicked is a great way to enhance user experience. This animation can flow seamlessly from right to left before disappearing, providing a visually engaging transition for users as they

Despite anticipating more negative responses than positive ones, I believe that even one correct answer outweighs it all! So, I'm trying to figure out how to create a loading animation that covers the entire screen whenever a button on the navigation ...

Is there a way to set a value within a jQuery function, and then invoke another function to utilize that value?

Suppose I have a function called isPercentage, which utilizes a value that is defined within the function it's being called in: isPercentage = function(){ if (value < 1){ value = value * 100; console.log(value); ...

What is the best method for fetching the values of a select element in React.js?

I'm struggling to retrieve the value of a selected element in a dropdown list. I've tried debugging it, but haven't been able to get the value. I attempted to console log e.target.value, but unfortunately, it didn't work. Any thoughts o ...

Leveraging JavaScript variables within a jQuery selector

My <form> includes the following input... Term ID: <input type="text" name="data_array[0][term_id]" size="5" value="' . $highest_term_id . '"> with the $highest_term_id being set by PHP. I am attempting to increment the "data_array ...