Reputation: 1663
I've read some articles about this stuff. However, I still get stuck in a point. For example, I have two function:
function getDataSync(){
var data = db.query("some query");
return JSON.stringify(data);
}
function getDataAsync(){
return db.query("some query",function(result){
return JSON.stringify(result);
});
}
People said that asynchronous programming
is recommended in IO bound. However, I can't see anything different in this case. The Async
one seems to be more ugly.
What's wrong with my point?
Upvotes: 1
Views: 287
Reputation: 256
nodejs is asynchronous by default which mean that it won't execute your statement in order like in other language for example
database.query("SELECT * FROM hugetable", function(rows) {
var result = rows;
});
console.log("Hello World");
In other language, it will wait until the query statement finish execution.
But in nodejs, it will execute the query statement separately and continue execute to log Hello World
to the screen.
so when you say
function getDataSync(){
var data = db.query("some query");
return JSON.stringify(data);
}
it will return data before db.query return data
function getDataAsync(){
return db.query("some query",function(result){
return JSON.stringify(result);
});
}
but in node.js way the function that pass as parameter is called callback which mean it will call whenever the getDataAsync()
finish its execution
We use callback in nodejs because we don't know when db.query()
finishes its execution (as they don't finish execution in order) but when it finishes it will call the callback.
Upvotes: 2
Reputation: 92925
Asynchronous is used when some operation blocks the execution. It is not an problem in Multi thread application or server. But NodeJS is single threaded application which should not blocked by single operation. If it is blocked by operation like db.query("some query");
, Node.js will wait to finish it.
It is similar to you just stands idle in front of rice cooker until it is cooked. Generally, you will do other activities while rice is cooking. When whistle blows, you can do anything with cooked rice. Similarly NodeJS will sends the asychronous operation to event loop which will intimate us when operation is over. Meanwhile Node.js can do processing other operation like serving other connections.
You said Ugly
. Asynchronous does not mean to use only callbacks
. You can use Promise, co routine or library async.
Upvotes: 0
Reputation: 22709
In your first example, the thread will get blocked at this point, until the data is retrieved from the db
db.query("some query");
In the second example, the thread will not get blocked but it will be available to serve more requests.
{
return JSON.stringify(result);
}
This function will be called as soon as the data is available from the db.
That's why node.js is called non-blocking IO which means your thread is never blocked.
Upvotes: 0