Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

210
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda