Reputation: 689
I'm running a simple node.js application that sends a JSON object upon http post. The application is using node-mysql and express modules.
Here is the code.
HTML:
$(document).ready(function () {
setInterval(function() {
var path = window.location.pathname;
$.ajax({
url: path,
type: "POST",
contentType: "application/json",
processData: false,
complete: function (data) {
var a = JSON.parse(data.responseText);
var display = "<ul style='list-style-type:none'>";
var count = 1;
for (var key in a) {
if (a.hasOwnProperty(key)) {
var str = a[key].split('|');
display += "<li style='background: #333; margin: 10px 0;'>" + str[0] + " <span style='color:#ddd;'>to " + str[1] + "</span></li>";
count++;
}
}
display += "</ul>"
$('#output').html(display);
}
});
}, 3000);
});
Page configuration:
app.get('/', function(req,res) {
res.sendfile(__dirname + '/index.html');
});
app.get('/docs', function(req,res) {
res.sendfile(__dirname + '/display.html');
});
app.get('/bio', function(req,res) {
res.sendfile(__dirname + '/display.html');
});
app.get('/int', function(req,res) {
res.sendfile(__dirname + '/display.html');
});
And one of the app.post methods used to send the JSON object upon page request. There are four, the root, which is just a list of links pointing to /docs, /bio, and /int.
app.post('/docs', function(req, res){
var query = "/* query */";
connection.query(query, req.body, function(err, rows, fields) {
if (err) throw err;
var obj = {};
var id = "";
for (var i = 0; i < rows.length; i++) {
id = "id" + i;
obj[prop] = rows[i].name + '|' + rows[i].counter_name;
}
res.send(JSON.stringify(obj));
});
});
The application runs and seems to update fine, but I'm not sure if it is asynchronous or not. Basically, just need to know if it is, and if it isn't some pointers to make it so.
Upvotes: 1
Views: 187
Reputation: 60414
Peppering your code with console.log
is a quick and dirty way to demonstrate that some function is running asynchronously:
console.log("before");
someFunction(param1, function() {
console.log("inside");
});
console.log("after");
If the function executes asynchronously, then you'll see something like this:
before
after
inside
It's not necessarily true that a function passed to another function as a callback will run asynchronously, but it's often the case. The only way to know for sure is to read the documentation or, better yet, test it.
Upvotes: 2
Reputation: 60768
Rule of thumb in node: unless the word "sync" occurs in the method name, all IO is asynchronous. This is essentially the point of node.
IO includes any time a file must be opened, which includes all connections, including HTTP connections, SQL connections, RabbitMQ connections, etc., and all files on disk, including log files, etc.
Typically to understand asynchronous code you should look for where the callbacks are. In Javascript callbacks are very often given as anonymous functions. e.g.
connection.query(query, req.body, function(err, rows, fields) {
// ^ anonymous function definition
The last argument is a callback. In general I would define a callback as a function that is passed as an argument to another function (often, but not always, as an anonymous function.) When that whole line of code is executed, the callback is of course not called. It's called when the definition of query
says to call it, which in this case will mean after the response to the query is received, which can be seconds later, and in particular long after the following code is executed, and in a call stack far away.
Callbacks are needed to achieve asynchrony because right after the connection.query
is called, the response hasn't come in yet. So it's impossible to do anything with the response, whether it's an error or rows. That needs to happen later, i.e. asynchronously. So you pass a callback to do that handling at some later point.
Upvotes: 2