hahamed
hahamed

Reputation: 329

Howto wait for query execution on database?

my code is:

        jsonArray.forEach(function (that) {
            db.each(sql, function (err, row) {
            }, function (err, rows) {
                console.log("111");
            });
        });
        console.log("222");

after running first write is 222. How to wait for db.each to write 111 then 222? thanks

EDITED:

console.log("222"); is after loop.

Upvotes: 0

Views: 1859

Answers (1)

cybersam
cybersam

Reputation: 66999

In order to make sure "222" is logged after "111", you'd have to do this:

jsonArray.forEach(function (that) {
    db.each(sql, function (err, row) {
    }, function (err, rows) {
        console.log("111");
        console.log("222");
    });
});

This is because the second function passed to db.each() is guaranteed to be called after the DB query has completed. Since the DB query is performed asynchronously, you cannot log "222" right after you initiate the query and expect it to reliably show up after "111".

Now, if you actually wanted "111" to print out with every result row, you want something like this:

jsonArray.forEach(function (that) {
    db.each(sql, function (err, row) {
        console.log("111");
    }, function (err, rows) {
        console.log("222");
    });
});

Upvotes: 2

Related Questions