Home > Mobile >  Why sometime I do get "Promise { <pending> }" response?
Why sometime I do get "Promise { <pending> }" response?

Time:01-12

I have a class like below:

class User implements IUser{

  static async findByEmail(email: IUser["email"]) {
    const users = await Pools.execute("SELECT * FROM users WHERE email = ?", [email]);
    if (!users.length || !users[0]) {
      return null;
    }
    return users[0];
  };



  static async count() {
    const count = await Pools.execute('SELECT COUNT(*) count FROM users;');
    try {
      if (!count.length || !count[0]) {
        return null;
      }
      console.log('this is from inside the count method', count[0]);
      return count;
    } catch (err) {
      throw err;
    }
  }
}

And calling the class methods like the following:

  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const existingUser = await Users.findByEmail(req.body.email);
      if (!existingUser) {
        throw new BadRequestError("Invalid credentials");
      }
      console.log(existingUser);
      const count = Users.count();
      console.log(count);
      }
   }

I get this results:

[
  {
    id: 1,
    email: '[email protected]',
    password: '12345',
    username: '[email protected]',
    admin: 1,
    created_at: 2023-01-06T02:31:14.000Z
  }
]
Promise { <pending> }
this is from inside the count method [ { count: 4 } ]

I have defined and used both functions in a similar way, but one of them works as expected but the other one returns Promise { <pending> } instead of [ { count: 4 } ] that the other console log returns from inside the count() function.

Why 2 similar methods work differently? How should I get the desired result([ { count: 4 } ]) from the second one?

CodePudding user response:

You forgot to await in this line:

console.log(existingUser);
const count = Users.count();  // here is missing the await
console.log(count);

change to this:

const count = await Users.count();
  • Related