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