Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

211
Views
How to wait for a function execution in NodeJS

, 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!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!