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?

kakoli
  • 423
  • 4
  • 8
  • 18
  • 2
    Please ask only one question per post. – Bergi Dec 05 '15 at 19:52
  • And make no mistake, JavaScript has nothing to do with Java, even though they have similar names. –  Dec 05 '15 at 19:54
  • 2
    "a Java backend which is more formal language". I don't know what this means. – Ben Aston Dec 05 '15 at 19:55
  • Regarding 1), have a look at [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/q/23667086/1048572) – Bergi Dec 05 '15 at 19:56

1 Answers1

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 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 05 '15 at 20:26