0

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?

2
  • I think this is a duplication to this: stackoverflow.com/questions/6638646/… Commented Jun 9, 2012 at 17:29
  • 1
    Firstly, get more familiar with what asynchronous stands for (Google is your friend on this one). Secondly, checkout this page. Commented Jun 10, 2012 at 2:16

2 Answers 2

0

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.

Sign up to request clarification or add additional context in comments.

Comments

0

async should work for you

async.series([
    function(){ ... },
    function(){ ... }
]);

See https://github.com/caolan/async#series

Comments

Your Answer

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.