I'm currently using SQLite 3 and I'm running a query that runs a callback function. This callback function stores all the results of the query in a function-level variable for access later on in the function. The callback along with the query seem to make the latter part of the function run thereby making the function-level variable empty. Is there a way to run the rest of the function only after the query completes?
var results = [];
var query = conn.query(q, function(error, result){
for (var i = 0; i < result.rowCount; i++) {
results.push(result.rows[i]);
}
console.log(results); // results is not empty here
} );
// console.log(results); // results is empty here
-
can you be more specific with what you are trying to achieve? Based on your question it seems you are aware of the async nature of javascript, so not really sure what is it you are asking.Chaim Friedman– Chaim Friedman2017年05月01日 02:32:19 +00:00Commented May 1, 2017 at 2:32
2 Answers 2
That is in the nature of how node's asynchronous functions work. Here's a nice read on how to control and organize how things are happening: Control flow
Basically, you are going to have to deal either with some levels of nesting or separating things in more functions.
var results = [];
var query = conn.query(q, function(error, result){
for (var i = 0; i < result.rowCount; i++) {
results.push(result.rows[i]);
}
console.log(results); // results is not empty here
// Do whatever you want next here
} );
or
var results = [];
var query = conn.query(q, function(error, result){
for (var i = 0; i < result.rowCount; i++) {
results.push(result.rows[i]);
}
console.log(results); // results is not empty here
continue();
});
function continue() {
// Do the next things here
}
Comments
var results = [];
var query = conn.query(q);
query.then(function(error, result){
for (var i = 0; i < result.rowCount; i++) {
results.push(result.rows[i]);
}
console.log(results); // results is not empty here
});