Home > Enterprise >  await doesnt work on nodejs project as expected
await doesnt work on nodejs project as expected

Time:09-25

Good day.

Im working on a express project and havent been ables to fully understan how async functions an promises work. This is my project structure

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

payment service is the implementation of a third-party payment tool, and it defines a method im using like this

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

im calling this method from my userController

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

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

but response is always undefined, it doesnt wait as i thought it shoudl do because of the "await" keyword.

How does this exactly works? what am i doing wrong if i want to make it wait till the response is returned?

CodePudding user response:

There's an issue in your code for the pay function:

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

You don't return anything. You just run service.pay(). Therefore, the signature of the function pay (declared on the first line) is a function that returns a promise, but the return type is Promise<void>, not Promise<YourData>. This causes it to always return undefined, even when called with await, like in your complete example code.

I notice you have the code return response; inside the "then" callback. This may mean you intended for that data to be returned to the caller of pay (not service.pay) when the data was ready. To do this, should rewrite your pay function in one of two ways:

  1. Replace service.pay ... with return service.pay ... so that the promise returned by service.pay is actually returned to the caller of pay.
  2. Rewrite it so that you remove the "then" callback and replace service.pay ... with return await service.pay .... You've already put in the work to design pay as an async function, so you can now use await inside it, which often makes this kind of code more straightforward to write and read later on.
  • Related