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.
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.
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:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.