【问题标题】:await is only valid in async function and async wrap returns undefined [duplicate]await 仅在 async 函数中有效,并且 async wrap 返回 undefined [重复]
【发布时间】:2022-08-18 00:10:55
【问题描述】:
const countUser = await Users.count();
console.log(countUser);

试图在数据库中获得计数。以上返回一个有效性错误。计数()是

顺便说一句,这里 count() 是 Sequelize Model.count() 方法用于生成和执行对连接数据库的 SELECT COUNT SQL 查询

像这样将它包装在 async/await 中

async function getUsers() {
    const countUser = await Users.count()
    return countUser;
}

它返回为

Promise { <pending> }
Executing (default): SELECT count(*) AS `count` FROM `users` AS `users`;

然后,将它包装在另一个 async/await 中作为承诺链,因为我认为这可能有效,但没有

async function getUsers() {
    const countUser = await Users.count()
    return countUser;
}

async function logUsers() {
    const userlog = await getUsers()
    console.log(userlog)
}

console.log(logUsers()) 返回相同的未决错误,因此值未定义。

有什么办法吗?

谢谢!

  • 也许您没有在异步函数中调用logUsers
  • logUsers需要等待(或者您可以使用.then 回调),就像getUsers 所做的一样。

标签: javascript async-await sequelize.js undefined


【解决方案1】:

我认为可能的解决方案是创建一个匿名异步函数

(async () => {
    await logUsers();
})();

【讨论】:

  • 为什么对这个投反对票,有人可以解释一下吗?
猜你喜欢
  • 2019-10-04
  • 2018-09-01
相关资源
最近更新 更多