Unexpected behavior is seen in the node.js project when using the "await" keyword

Hey there!

I've been tinkering with an Express project lately and I'm having a bit of trouble grasping the ins and outs of async functions and promises. Here's how my project is structured:

-controllers --userController.js -services --paymentService.js

The payment service handles integration with a third-party payment tool, and it defines a method that looks like this:

const pay = async(data) => {
    service.pay()
        .then(function(response){
            return response;
        }).catch(function(err)){
             console.log(err);
        });
} 

I'm trying to call this method from my userController:

let payUser = async(req, res) => {

    const response = await paymentService.pay(req.data);
    if(response) {
        res.send(response)
    }
}

However, the response always ends up being undefined. It doesn't seem to wait as expected because of the "await" keyword.

How exactly does this work? What am I missing if I want to ensure it waits until the response is returned?

Answer №1

Your code has an issue with the pay function:

const pay = async(data) => {
    service.pay()
        .then(function(response){
            return response;
        }).catch(function(err)){
             console.log(err);
        });
} 

The problem is that you are not returning anything in your function. Instead, you are just calling service.pay(). As a result, the function pay is supposed to return a promise but its return type is actually Promise<void> instead of Promise<YourData>. This causes it to always return undefined, even when using await.

If you intended for the data from response to be returned to the caller of pay, you should consider one of the following solutions:

  1. Replace service.pay ... with return service.pay ... so that the promise from service.pay is actually returned.
  2. Remove the "then" callback and use return await service.pay .... Since pay is already an async function, using await can simplify your code and make it easier to read.

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

Guide on parsing the obj variable into a webix .show() modal?

I have a piece of code that looks like this: $$('TLVab').attachEvent("onAfterEditStop", function(state, editor, ignoreUpdate) { $$('deleteLTMPopup').show();//TODO parse state into the pop up }); UI.deleteLTMPopup= {id:& ...

"Learn how to properly configure JSON data on x and y axes in the c3.js library

I rely on c3 to produce uncomplicated graphs. I am in search of a way to extract data from a Json file and use it to create my Line Graph. In order for the graph to display correctly, I need my Y values to be represented by "Labels" and my X values to be ...

Refreshing a nested object by modifying its array elements in JavaScript

Hello, I am looking for assistance in updating the userSettings variable. Specifically, when a product is removed from the products array, I need to update the sortedProducts array within the userSettings.categories array. I have attempted to accomplish th ...

Unable to send email using node-mailer | Sender address "[email protected]>" is invalid

I am attempting to use express, nodemailer, and express to test the functionality of sending emails via a Gmail account. However, I am encountering a problem as the email is not being sent despite the email address and password being correct. The error mes ...

js include exclude switch a category

Although this question has been asked before, I have a query on completely removing an "id" from an element. Let's consider the following scenario: <div id="page"> some content here </div> I want to eliminate the "id" attribute from the ...

Utilizing loops to generate multiple arrays from a given string

I have a sequence of values: "000111111122222223333333444455556666" Is it possible to utilize three separate loops to generate multiple arrays based on different index ranges? For instance, producing an array from index 0 to 3 ([000]), then creating arr ...

Prevent page refresh when submitting a form using PureCSS while still keeping form validation intact

I'm currently implementing PureCSS forms into my web application and facing a challenge with maintaining the stylish form validation while preventing the page from reloading. I discovered that I can prevent the page reload by using onsubmit="return f ...

How can I automatically add a specific word that I've highlighted within a <text area> situated within an iframe?

This chrome plugin automatically inserts a designated word into the content of an iframe. Specifically designed for Chrome users. <html> <iframe id="iframe" frameborder="0" src="http://www.maozakor.co.il/demo/default.aspx"> </if ...

Issue with conditional image source URL in NUXT component not functioning as expected

I am currently attempting to dynamically render an image source path based on the provided prop in the component. In case the image does not exist in the assets folder, I want to include a fallback path. Below is the code snippet for my image tag: <img ...

Using Django to load a template and incorporate a loading spinner to enhance user experience during data retrieval

In my Django project, I need to load body.html first and then dashboard.html. The dashboard.html file is heavy as it works with python dataframes within the script tag. So, my goal is to display body.html first, and once it's rendered, show a loading ...

Checkbox selection causing Bootstrap accordion to collapse

Hey everyone, I'm currently working with Bootstrap 5 accordion and facing an issue where the input checkbox is triggering the "collapse" event of the accordion. I attempted to relocate the checkbox outside the scope of the accordion button but that so ...

Jest is simulating a third-party library, yet it is persistently attempting to reach

Here's a function I have: export type SendMessageParameters = { chatInstance?: ChatSession, // ... other parameters ... }; const sendMessageFunction = async ({ chatInstance, // ... other parameters ... }: SendMessageParameters): Promise<vo ...

Is there a way to select an element within a nested list item only when the preceding list item is clicked using Jquery/JavaScript?

I am working with an unordered list that looks like this: <ul> <li><a class="foo" id="one">some text</a></li> <li><a class="foo" id="two">some text</a></li> <li><a class="foo" id="thr ...

Storing Query Results in a Variable in Node.js

When attempting to print out the customerData variable, I am getting an undefined value even though I need to see what it returns. if( phone === "" || phone === null || phone === undefined ) { var customerData = pool.query('SEL ...

Displaying JSON data obtained from two separate arrays in AngularJS - is it possible?

I want to display the value of my Json element, "Baru20151","Lama20151","Baru20152","Lama20152", but I'm unsure how to do it. The element is fetched from 2 arrays, for the "Baru20151" elements, "20151" is obtained from the "isimasa" array in my Jso ...

Using jQuery to verify the existence of a lengthy object

Is it possible to achieve this functionality using jQuery or other libraries? Dojo has this feature, but what about the others? $.ifObject(foo.bar.baz.qux[0]) if (foo && foo.bar && foo.bar.baz && foo.bar.baz.qux[0]) With an unkno ...

Updating fields in Mongoose documents atomically

I am facing an issue with my app where users can only increment the value once, but the code I have written is failing due to the asynchronous nature of the update function in mongoose. The problem arises because my check if(user.valueIncremented) does not ...

Angular 17: Issue with _HttpClient Provider Not Found in Standalone Component Utilizing ApiService

I have been developing a cutting-edge Angular 17 application that integrates the Spotify API using the innovative standalone component functionality. However, I am facing an issue while attempting to inject the HttpClient into a service. Despite meticulous ...

Issue with Jenkins running Cucumber causing timeout on JavaScript form

My current setup involves Cucumber 1.2.1 with Watir-webdriver 0.6.1 for webpage testing. While the tests run smoothly on my local machine, I encounter a timeout issue on a CI machine (Jenkins) when trying to fill out a javascript form. Despite having emai ...

Adjusting the StrokeWidth in pixels/em units on fabricjs

When adding a rectangle or circle to the canvas and adjusting the strokeWidth using a range input, how can we determine the value of strokeWidth in pixels, em, or percent? For instance, if we set strokeWidth to 5 within a range of 1-10, how much does the a ...