Javascript – the difference between synchronous and asynchronous programming (in node.js)


I've been reading nodebeginner
And I came across the following two pieces of code.

The first one:

    var result = database.query("SELECT * FROM hugetable");
    console.log("Hello World");

The second one:

    database.query("SELECT * FROM hugetable", function(rows) {
       var result = rows;
    console.log("Hello World");

I get what they're supposed to do, they query the database to retrieve the answer to the query. And then console.log('Hello world').

The first one is supposedly synchronous code.
And the second one is asynchronous code.

The difference between the two pieces is very vague to me. What would the output be?

Googling on asynchronous programming didn't help me either.

Best Solution

The difference is that in the first example, the program will block in the first line. The next line (console.log) will have to wait.

In the second example, the console.log will be executed WHILE the query is being processed. That is, the query will be processed in the background, while your program is doing other things, and once the query data is ready, you will do whatever you want with it.

So, in a nutshell: The first example will block, while the second won't.

The output of the following two examples:

// Example 1 - Synchronous (blocks)
var result = database.query("SELECT * FROM hugetable");
console.log("Query finished");
console.log("Next line");

// Example 2 - Asynchronous (doesn't block) 
database.query("SELECT * FROM hugetable", function(result) {
    console.log("Query finished");
console.log("Next line");

Would be:

  1. Query finished
    Next line
  2. Next line
    Query finished

While Node itself is single threaded, there are some task that can run in parallel. For example, File System operations occur in a different process.

That's why Node can do async operations: one thread is doing file system operations, while the main Node thread keeps executing your javascript code. In an event-driven server like Node, the file system thread notifies the main Node thread of certain events such as completion, failure, or progress, along with any data associated with that event (such as the result of a database query or an error message) and the main Node thread decides what to do with that data.

You can read more about this here: How the single threaded non blocking IO model works in Node.js