0

Coming from a Java backend which is more formal language with strong syntaxes and no function passing, I have some beginner queries on JavaScript execution.

var mongodb = require('mongodb');
var mongoClient = mongodb.MongoClient;
var dbUrl = 'mongodb://localhost:27017/test';
var con;

function callback(err, db) {
    if (err) console.log('Unable to connect to the mongoDB server. Error:', err);
    else {
        console.log('Connection established to', dbUrl);
        con = db;
        findEmps(con, function() {
            console.log("After find");
            con.close();
        });
    }
}
mongoClient.connect(dbUrl, callback);

function findEmps(db, callback) {
    var cursor = db.collection('emp').find();
    //iterate on the result
    cursor.each(function(err, result) {
        assert.equal(err, null);
        if (result != null) {
            console.dir(result);
        } else { //end of cursor where result is null 
            console.log("In ELSE");
            callback(err, con);
        }
    });
}
console.log("END");

Why is END being printed first?

4

1 Answer 1

1

Most of what you are doing involves the use of callbacks.

You are passing a function as an argument to another function. The other function then calls it. It might not (and in these cases does not) call it immediately.

mongoClient.connect(dbUrl, callback);

This, essentially, tells another process to start connecting to the database. When that process reports back with a connection, the callback function is called.

In the meantime, the rest of the program (console.log("END");) continues to execute.

Get used to making callback functions (instead of return values) being responsible for dealing with responses to such asynchronous operations.

1
  • I guess for the same reason, con.close() cannot be called after console.log("END"). So it has to be called in the callback function.So the key here is async programming.
    – kakoli
    Dec 5, 2015 at 20:26

Not the answer you're looking for? Browse other questions tagged or ask your own question.