如何在 NodeJS 中等待函数执行

How to wait for a function execution in NodeJS

, 我最近开始使用NodeJS编程,所以我是一个初学者。我正在使用 Sequelize。当我调用函数 sequelize.sync() 时,它会在我的数据库中创建表(我定义的)。无论如何,如果我在 sequelize.sync() 函数之后立即执行查询,我会得到一个错误。我认为问题是查询在 sequelize.sync() 结束之前执行,所以我需要等待 sequelize.sync() 执行结束。代码很简单:

sequelize.sync({force: true});
Users.create({name: "A", surname: "B", number: 1});

错误是:

(node:2561) UnhandledPromiseRejectionWarning: Error
    at Query.run (/mnt/c/Users/raffa/Desktop/simple_app/node_modules/sequelize/lib/dialects/postgres/query.js:50:25)
    at retry (/mnt/c/Users/raffa/Desktop/simple_app/node_modules/sequelize/lib/sequelize.js:313:28)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:2561) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)

我该如何解决这个问题?谢谢!

要等待 returns Promise 的异步函数,例如 sequelize.sync(),您只需添加 await 关键字。

await sequelize.sync({force: true});
Users.create({name: "A", surname: "B", number: 1});

如果您想在之后做点什么,也不要忘记等待 Users.create。通常最好的做法是始终等待异步函数。

注意:Top-level await 仅适用于 ESModules。否则,您必须将整个代码包装在异步 IIFE