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

137
Visualizações
Wait for result of query

JavaScript code:

let result = db.all(query, [], (err, rows) -> {
   return rows;
});
return result

It doesn't work and the function returns Database{}. By logging I found out the function first returns result and only later returns rows, i.e. it doesn't wait for db.all(...) to be executed.

How do I get the code to execute in the correct order: first execute db.all, wait until db.all returns a value, and only after that return result? And why does the compiler reorder this when it's obvious the value of result depends on db.all(...)?

almost 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You are dealing with asynchronous code and callback functions The dependency that you are using, uses anonymous callback functions to handle the asynchronous execution of your query. After the db has executed the query, the result is in the "rows" parameter of your callback function.The compiler does behave as expected.

In order to make the code asynchronous, you might want to consider using a Promise approach.

let requestPromise = new Promise((resolve, reject) => {
  //your code goes here
  db.all(query, [], (err, rows) => {
    //in case of error //reject(err)
    //otherwise
     resolve(rows);
  });
})
//return await requestPromise

Keep in mind that the function you are calling this from, also needs to be async. More information in the links provided.

almost 4 years ago · Santiago Trujillo 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