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?
asynchronousstands for (Google is your friend on this one). Secondly, checkout this page.