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

134
Views
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 answers
Answer question

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