I\'ve been reading nodebeginner And I came across the following two pieces of code.
The first one:
var result = database.query(\"SELECT * FROM hu
This would become a bit more clear if you add a line to both examples:
var result = database.query("SELECT * FROM hugetable");
console.log(result.length);
console.log("Hello World");
The second one:
database.query("SELECT * FROM hugetable", function(rows) {
var result = rows;
console.log(result.length);
});
console.log("Hello World");
Try running these, and you’ll notice that the first (synchronous) example, the result.length will be printed out BEFORE the 'Hello World' line. In the second (the asynchronous) example, the result.length will (most likely) be printed AFTER the "Hello World" line.
That's because in the second example, the database.query
is run asynchronously in the background, and the script continues straightaway with the "Hello World". The console.log(result.length)
is only executed when the database query has completed.