[英]Why sometime I do get "Promise { <pending> }" response?
I have a class like below:我有一个如下所示的 class:
class User implements IUser{ class 用户实现 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:并像下面这样调用 class 方法:
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.我以类似的方式定义和使用了这两个函数,但其中一个按预期工作,但另一个返回Promise { <pending> }
而不是[ { count: 4 } ]
另一个控制台日志从count()
function。
Why 2 similar methods work differently?为什么两种相似的方法效果不同? How should I get the desired result( [ { count: 4 } ]
) from the second one?我应该如何从第二个得到想要的结果( [ { count: 4 } ]
)?
You forgot to await
in this line:你忘了在这一行中await
:
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.因为count()
是一个异步 function。除非您等待,否则异步将主要返回带有 promise 的每个值。 You can see more discussion in this question.您可以在这个问题中看到更多讨论。 async/await implicitly returns promise? 异步/等待隐式返回 promise?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.