1

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?

1
  • 2
    Since you got two answer without anyone pointing it out, I just have to make clear that the second example can never work. You have to use callbacks in your own functions too: function getDataAsync(callback){ db.query("some query",function(result){ callback(JSON.stringify(result)); }); } (sorry for the inline formatting). Commented Jul 29, 2014 at 9:37

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

7 Comments

I don't have console.log("Hello World"); at later point. And also, I don't need to know when the query finish. So do I need an Async function in this case?
If you use node.js, you can't just put JSON.stringify(result); after a query like that because you don't know whether db.query finish execution before the JSON.stringify() start executing (and probably not and you will stringify an null variable). So the callback is needed. In nodejs you put statement in order when it can run parallel that you don't want your program to freeze and wait when the previous statement is executing.
I got your point. However, I just think that the freeze time is small, because it still need to wait unti the data is available.
Normally in other language which is IO blocking if the freeze time is so long your program can't do anything else so in some case when you have other IO statement to do nodejs can do it for you as it not block your request until the previous one finished, so it can be faster. But in some case you can't do that for ex. you have to do some complicated computation then nodejs won't be anything faster than other programming language.
ok, the concept of nodejs is that it uses one thread to handle everything and throw some IO work like database query to someone responsibity and comeback when he tell him that his work is finish. but nodejs can't throw some work that he is responsibled to like computation. the whole idea is that normally when you do some io your cpu become idle nodejs just want to maximize to usage of the cpu so he doesn't wait for other people's job and come back to work more try this link : greenash.net.au/thoughts/2012/11/…
|
0

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.

4 Comments

And this is why Promise exists :) google.fr/…
Thank you, I got your point. BTW, do you mean that I should use Async in every cases?
Do you have an option with node.js ?
What's about a case that the thread get blocked but the amount of blocked time is small? Can I use Sync instead of Async?
0

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.

3 Comments

What's happened if the amount of waiting time is small? Do I need Async in this case?
@user3828771 It doesn't matter howsoever small time it takes, if it waits at all it needs to be Async. It's more about the control flow, the task being carried out without stopping at all, in one go; if it can then its sync, but if it breaks up and has to wait for an external factor then its async. read this
Node.js has decided to include synchronous functions to maintain a similitude with other common languages, but they shouldn't be used, never, never, never!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.