async/await inexpressive not able to return properly

Currently, I am working on a project involving an express app and incorporating async/await in my routes. However, I've encountered an issue where it seems to be skipping the wait for the findOneUser call to complete before moving on to the next line:

app.post ('/api/authenticate', async(req, res) => {
  console.log('GET TO AUTHENTICATE')
  const { email, password } = req.body;
  const user_db = await users.findOneUser( email );
  console.log("user_db", user_db)
  return user_db
});

 const findOneUser = (email) => {
    console.log("email", email)
     pool.query('SELECT * FROM users where email = $1', [email], (error, results) => {
      if (error) {
        throw error
      }
      console.log("RESULT", results.rows)
       results.rows
    })
  }

In the terminal logs below, you can observe that the user_db_log appears before the RESULT log. According to my understanding of async/await, the user_db code should have waited for the execution of the user.findOneUser method:

GET TO AUTHENTICATE

email

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d58455c504d51587d52484951525256135e5250">[email protected]</a>

user_db undefined

RESULT 

[
  {
    id: 11,
    first_name: 'Test',
    last_name: 'User',
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="01756472757472647341756472752f626e6c">[email protected]</a>'
  }
]

Answer №1

Here's a suggestion on how to approach this using Promise and async/await

 app.post ('/api/authenticate', async(req, res) => {
      console.log('GET TO AUTHENTICATE')
      const { email, password } = req.body;
      const user_db = await users.findOneUser(email);
      console.log("user_db", user_db)
      return user_db;
    });


 const findOneUser = async (email) => {
        var myProm = () => {
            return new Promise((resolve, reject) => {
                pool.query('SELECT * FROM users where email = $1', [email], (error, results)=> {
                    error ? reject(error) : resolve(results);
                });
            });
        }
        var result = await myProm();
        return result;
  }

Answer №2

Waiting for Awaits: Understanding how await functions wait for promise resolution.

When it comes to your findOneUser function, the problem lies in the fact that it does not return a promise, causing await to execute immediately and return.

To fix this issue, either add async functionality to your findOneUser function (which wraps the response in a promise) or create a new promise within the function and wrap the response before returning it.

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

issue with webpack-dev-server not refreshing after changes to HTML or Sass files

Here is the layout of my project: \root \webpack.config.js \public \ index.html \ ... \ css \ directives \ views \ dist (webpack output) \app.js ...

What is the best way to sift through an array containing arrays?

Looking for help with filtering and pushing data from a JSON array? Specifically, I need to filter arrays where the data's attrs property includes a src attribute. It's proving challenging for me, so any assistance would be greatly appreciated. ...

Emphasizing the content of the text file with the inclusion of span tags

I am relatively new to working with angular js and javascript. I have a document or text file that looks something like this: Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dumm ...

Mutual TLS authentication and secure tunneling with ngrok

I am currently working on integrating a Payment Method with Shopify that requires me to validate their client requests using mTLS. Payment apps must utilize mTLS for processing all requests where they act as the server and Shopify as the client. This is ...

Leveraging the power of AngularJS to run JavaScript functions saved as strings

Is it possible to dynamically inject JavaScript code that is stored in a string into AngularJS controllers? var dynamicJS = "function DoSomething(value){var x = 1+1 return 2;}" I need to inject the above function dynamically into my AngularJS controller ...

Insert a hyperlink button using InnerHtml

I am facing an issue with displaying a list item that contains a tab and a link button: <li runat="server" id="liActivityInvoices"><a href="#tabActivityInvoices">Invoices</a><asp:LinkButton runat="server" ID="btnLoadInvoice" OnClick=" ...

Arrow in addition to the bootstrap container

I am working with a bootstrap container that is centered on the page with margins on both sides. What I want to do is add two arrows, one on each side of the container, pointing left and right. The reason for this is because I am trying to create a carous ...

What could be the reason for the empty array returned by the combinationSum function in Javascript?

The combinationSum function is returning an empty resultArr. When checking the ds array with console.log, it shows the correct answer, but for some reason, the final output array ends up being [[],[]]. var combinationSum = function(candidates, target) { ...

Tips for inserting a value into a specific location within an array using JavaScript

I am working with an array of objects that looks like this: const array = [ { id: 1 }, { id: 2 }, { id: 3 }, { id: 4 } ]; My task is to add a new entry to this array, but it needs to be inserted at a specific position. For instance, when adding { ...

Attempting to create a JavaScript calculator from scratch

After spending hours typing and debugging my code for a school assignment, I have created a calculator that still isn't working. I'm hoping someone can help me find the errors in my code. function myStory() { window.alert ("Very doge"); } // ...

Unable to retrieve obj after using $location.url

I am working with two different views. In the first view, I call a function from the admin controller using AngularJS: <a ng-click="updateAdmin(admin)">update</a> The code in the admin controller looks like this: $scope.updateAdmin = functio ...

Having Issues with Cookie Management in Express.js - Struggling to Assign Cookies

Greetings fellow developers, I'm a beginner in the world of programming and currently delving into the realm of web development using Node.js and Express. A sticky situation has arisen in my server related to cookie management, and despite my best ef ...

What is the best way to refresh my useEffect hook when a State change occurs in another component's file in ReactJS?

Seeking to execute an API call within useEffect() and aiming for the useEffect() function to trigger every time new data is appended to the backend. To achieve this, a custom button (AddUserButton.js) has been created to facilitate adding a new user to the ...

"Customized redirection based on user activity, providing unique paths for both login and

Currently, I am integrating the passport module for GitHub authentication into my app. I need to handle redirection based on the action performed by the user - whether it is a normal login or their first time logging in. passport.use(new GitHubStrategy({ ...

Dynamic HTML DOM element name changes

One thing I'm considering is the process of dynamically changing element names in the DOM with JavaScript or jQuery when adding or removing child elements. For instance, if I decide to delete the second text box from a form that originally has three t ...

Is it feasible to run a different route handler prior to executing the current one?

As I worked on creating an express node app, a question crossed my mind. Imagine there are two paths in the app: "/posts/:postId/update" "/posts/:postId/upload" I began to wonder - is it possible for the second path to automatically trigger the handle ...

Different results can be observed when comparing the array ordering in JavaScript between IE8 and Chrome

The array presented with items listed in specific order: { "5":{ "Title":"Title A", "Desc":"Description A" }, "15":{ "Title":"Title B", "Desc":"Description B" }, "10":{ "Title":"Title C", "Desc":"Description C ...

The animation of each individual node is not being displayed

I am following Clement's Pathfinding visualizer tutorial on YouTube to create a node by node animation, but I'm having trouble rendering the animation even with the delay provided for each node. Could you please review my code and help me figure ...

Debugging in Javascript involves pausing or breaking at every instance of a javascript function being called

I am currently working on unraveling a complex legacy JavaScript codebase, and I'm finding it challenging to determine where to place breakpoints (having to locate the files and set a breakpoint in Firebug, etc). Is there a way for Firebug to automat ...

eliminate item from list upon user clicking the button

Does anyone have any tips on how to effectively store and remove user-selected items from an object in JavaScript? I'm encountering an issue where only the first object in the array is being removed, and not the others. Any help would be appreciated! ...