Home > Blockchain >  How to wait for a function execution in NodeJS
How to wait for a function execution in NodeJS

Time:03-30

, I recently started programming in NodeJS, so I am a beginner. I'm using Sequelize. When I call the function sequelize.sync(), it creates the tables (that I defined) into my database. Anyway, if I perform a query immediately next the sequelize.sync() function, I obtain an error. I think that the problem is that the query is executed before the end of sequelize.sync(), so I would need to wait for the end of the execution of sequelize.sync(). The code is simply this:

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

The error is:

(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)

How can I solve this problem? Thank you!

CodePudding user response:

To wait for an asynchronous function that returns a Promise, like sequelize.sync(), you simply add the await keyword.

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

Don't forget to await the Users.create as well if you want to do something after. It's generally best practice to always await asynchronous functions.

Note: Top-level await is only available with ESModules. Otherwise you have to wrap the entire code in an async IIFE

  • Related