简体   繁体   中英

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

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?

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();

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM