await always thows SyntaxError: await is only valid in async function in sequelize

await always thows SyntaxError: await is only valid in async function in sequelize

Ubuntu 20
Node 12.18.4
NPM 6.14.6
Sequelize 6.3.5

我按照官方指南操作的,现在很困惑。
成功配置Sequelize并连接后,我尝试运行(来自官方文档)

await sequelize.authenticate();

它抛出 SyntaxError: await is only valid in async function

在官方入门页面https://sequelize.org/master/manual/getting-started.html下,明确指出:

Most of the methods provided by Sequelize are asynchronous and therefore return Promises. They are all Promises , so you can use the Promise API (for example, using then, catch, finally) out of the box.
Of course, using async and await works normally as well.

你必须像这样使用异步函数

getStateById: async (req, res) => {
              ^^^^^^

    sequelize.sequelize.transaction(async (t1) => {

        let state = await sequelize.state.findOne({
            where: {
                id: req.params.id
            }
        });

        let result = error.OK;
        result.data = state;

        logger.info(result);
        return res.status(200).send(result);
    }).catch(function (err) {
        logger.error(err);
        return res.status(500).send(error.SERVER_ERROR);
    });
}

当你想在你的应用程序中使用 await 时,async 是必需的,它只会在 async 函数类型中使用

这意味着在你的函数中如果你必须等待你需要声明一个异步外部函数:

async function() {
     await sequelize.authenticate();
}

const nameYourFunction = async () => {
     await sequelize.authenticate();
}

记得在 await 之前声明 async 或者如果你不想声明 async await 也可以使用 promise

const nameYourFunction = () => {
  sequelize
    .authenticate()
    .then((result) => {
      console.log('nameYourFunction -> result', result);
    })
    .catch((error) => {
      console.log('nameYourFunction -> error', error);
    });
};