Azeirah Azeirah - 1 year ago 90
Node.js Question

What is 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.

Answer Source

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 wont.

The output of the following two examples:

//example 1
var result = database.query("SELECT * FROM hugetable");
console.log("query finished");
console.log("Next line");

//example 2
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.
You can read more about this here: How the single threaded non blocking IO model works in Node.js

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download