[英]how to use execute in node-vk-bot-api? why do I get promise { <pending> }?
[英]Why sometime I do get "Promise { <pending> }" response?
我有一個如下所示的 class:
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;
}
}
}
並像下面這樣調用 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);
}
}
我得到這個結果:
[
{
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: 4 } ]
另一個控制台日志從count()
function。
為什么兩種相似的方法效果不同? 我應該如何從第二個得到想要的結果( [ { count: 4 } ]
)?
你忘了在這一行中await
:
console.log(existingUser);
const count = Users.count(); // here is missing the await
console.log(count);
更改為:
const count = await Users.count();
因為count()
是一個異步 function。除非您等待,否則異步將主要返回帶有 promise 的每個值。 您可以在這個問題中看到更多討論。 異步/等待隱式返回 promise?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.