0

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: 'admin@u.com',
    password: '12345',
    username: 'admin@u.com',
    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?

starball
  • 20,030
  • 7
  • 43
  • 238
best_of_man
  • 643
  • 2
  • 15

2 Answers2

4

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();
JuanDM
  • 1,250
  • 10
  • 24
1

Because count() is a async function. Async will mostly returns every value with a promise unless you awaits. You can see more discussion in this question. async/await implicitly returns promise?

Chit Khine
  • 830
  • 1
  • 13
  • 34