I'm using Javascript MYSQL Library from Node.js and then i have multiple queries to run in loop. But when i run the loop, the loop
always reach to end (done) suddenly while the Queries it started are still processing. So how do i keep the loop to wait each Query til done and then continue normally?
My code is:
function startHere() {
console.log("-- START --");
for (i=1; i < 6; i++) {
dbInsert(i);
}
console.log("-- END --");
}
function dbInsert(id) {
connection.query (
'INSERT INTO table SET data=?',
[id],
function selectCb(err, results, fields) {
if (err) {
console.log(err.message);
}
if (results.length > 0) {
console.log(id+" RECORDS ADDED!");
}
}
);
}
startHere();
When i run it, it always returns like:
-- START --
-- END --
1 RECORDS ADDED!
2 RECORDS ADDED!
3 RECORDS ADDED!
4 RECORDS ADDED!
5 RECORDS ADDED!
It means, the loop doesn't wait the end of the queries it started.
How can i detect the end-point of the queries and make it work?
Your selectCb method is not being called synchronously, so your loop is effectively firing off each call and then returning.
You can either check the docs for a synchronous version of that connection.query method, or you will need to create a callback to print the end message after all your inserts have fired.
async
should work for you
async.series([
function(){ ... },
function(){ ... }
]);