2

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 
asked May 1, 2017 at 2:20
1
  • 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. Commented May 1, 2017 at 2:32

2 Answers 2

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
}
answered May 1, 2017 at 2:50
Sign up to request clarification or add additional context in comments.

Comments

0
 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
 });
answered May 1, 2017 at 2:38

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.