1

I am reading The Node Beginner Book. In the chapter Event-driven asynchronous callbacks, the author gives an example to illustrate the idea of asynchronous callbacks. The code example is like:

var result = database.query("SELECT * FROM hugetable");
console.log("Hello World");

After adding a callback function to database.query, the code becomes asynchronous:

database.query("SELECT * FROM hugetable", function(rows) {
    var result = rows;
});
console.log("Hello World");

My question is why the database.query() function becomes asynchronous simply after adding a callback function. I have no experience with Javascript and JQuery before, that might be the reason I cannot understand.

2 Answers 2

3

There are many functions in node.js that have both an asynchronous flavor and a synchronous flavor. For example, there are two ways to read the contents of a file (docs):

//asynchronous
fs.readFile("filename.txt", function(err, data) {

});

//synchronous
var data = fs.readFileSync("filename.txt");

The example the author provides does in fact look somewhat confusing, but its possible that the database.query makes an asynchronous call depending on whether a callback is passed in as the second argument.

For example, it could be implemented something like this:

function query(queryString, callback) {
  if(callback !== undefined) {
    queryInternal(queryString, callback);
    return;
  }
  else {
    return queryInternalSync(queryString);
  }
}

In general, I think the convention is that a function is either asynchronous or synchronous (not both) so your intuition is right.

Note that in the synchronous case, console.log will be executed after result has the queried contents whereas in the asynchronous case, console.log will be executed as soon as query function returns and before callback is executed.

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

Comments

1

Asynchronously means it don't waits for the response and go to the next statements to be executed

In your second example the callback function handles your response while executing this, it doesn't waits and console.log("Hello World"); shows the output in console.

Read this:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.