javascript - What is the difference between synchronous and asynchronous programming (in node.js) -
i've been reading nodebeginner , came across following 2 pieces of code.
the first one:
var result = database.query("select * hugetable"); console.log("hello world");
the second one:
database.query("select * hugetable", function(rows) { var result = rows; }); console.log("hello world");
i they're supposed do, query database retrieve answer query. , console.log('hello world')
.
the first 1 supposedly synchronous code. , second 1 asynchronous code.
the difference between 2 pieces vague me. output be?
googling on asynchronous programming didn't me either.
the difference in first example, program block in first line. next line (console.log
) have wait.
in second example, console.log
executed while query being processed. is, query processed in background, while program doing other things, , once query data ready, whatever want it.
so, in nutshell: first example block, while second won't.
the output of following 2 examples:
// example 1 - synchronous (blocks) var result = database.query("select * hugetable"); console.log("query finished"); console.log("next line"); // example 2 - asynchronous (doesn't block) database.query("select * hugetable", function(result) { console.log("query finished"); }); console.log("next line");
would be:
query finished
next line
next line
query finished
note
while node single threaded, there task can run in parallel. example, file system operations occur in different process.
that's why node can async operations: 1 thread doing file system operations, while main node thread keeps executing javascript code. in event-driven server node, file system thread notifies main node thread of events such completion, failure, or progress, along data associated event (such result of database query or error message) , main node thread decides data.
you can read more here: how single threaded non blocking io model works in node.js
Comments
Post a Comment