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?

user3828771
  • 1,603
  • 3
  • 14
  • 14
  • 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). – Andreas Hultgren Jul 29 '14 at 09:37

3 Answers3

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.

gentlerainsky
  • 256
  • 2
  • 13
  • 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? – user3828771 Jul 29 '14 at 09:44
  • 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. – gentlerainsky Jul 29 '14 at 09:51
  • 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. – user3828771 Jul 29 '14 at 09:59
  • 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. – gentlerainsky Jul 29 '14 at 10:17
  • 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 : http://greenash.net.au/thoughts/2012/11/nodejs-itself-is-blocking-only-its-io-is-non-blocking/ – gentlerainsky Jul 29 '14 at 10:55
  • Do you mean that I can use `Sync` in non IO cases? – user3828771 Jul 29 '14 at 11:06
  • Only I/O is async, I mean you need to be sync when you use non I/O and there will be no speed up at all. But when you use I/O you can choose whether you want sync or async for ex. fs.readFile and fs.readFileSync. You should use async function whenever it is possible and aync is the main reason why you use nodejs. Try google about non I/O blocking vs I/O blocking to understand more. – gentlerainsky Jul 30 '14 at 09:09
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.

Madhur Ahuja
  • 22,211
  • 14
  • 71
  • 124
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.

Community
  • 1
  • 1
Fizer Khan
  • 88,237
  • 28
  • 143
  • 153
  • What's happened if the amount of `waiting time` is small? Do I need `Async` in this case? – user3828771 Jul 29 '14 at 10:01
  • @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](http://book.mixu.net/node/ch7.html) – laggingreflex Jul 29 '14 at 10:23
  • 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! – Fizer Khan Jul 29 '14 at 13:02