NodeJS 为什么有时我会收到“Promise {< pending>}”响应?

oknrviil  于 2023-01-12  发布在  Node.js
关注(0)|答案(2)|浏览(206)

我有一个类如下:
类用户实现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;
    }
  }
}

和调用类方法,如下所示:

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

我得到的结果是:

[
  {
    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 } ]

我以类似的方式定义和使用了这两个函数,但其中一个函数按预期工作,而另一个函数返回Promise { <pending> },而不是另一个控制台日志从count()函数内部返回的[ { count: 4 } ]
为什么两个相似的方法工作不同?我应该如何从第二个得到想要的结果([ { count: 4 } ])?

3yhwsihp

3yhwsihp1#

您忘记在此行中使用await

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

更改为:

const count = await Users.count();
gk7wooem

gk7wooem2#

因为count()是一个异步函数。除非你等待,否则异步函数通常会返回每个值。你可以在这个问题中看到更多的讨论。async/await implicitly returns promise?

相关问题