After playing with Node.js and reading about async i/o & evented programming a lot I\'m left with some question marks.
Consider the following (pseudo) code:
Run parrallel async code pattern:
To 'Wait for result from both async functions' you can do: in both async calls callbacks check both result and if all ready, call your DoSomethingWithTwoDependantResults.
In your example you probably need to execute queries sequentially:
query(sql1, function(sqlres1) {
query(sql2, function(sqlres2) {
writeResultUsingDataFrom(sqlres1, sqlres2);
}
});
your original code, modified to execute two queries in parallel:
function writeReply(res, template, username, event_name)
{
var body = renderView(username, event_name, template);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write(body);
res.end();
}
function onRequest(request, response)
{
// some non-blocking db query
query('SELECT name FROM users WHERE key=req.params['key']', function (err, results, fields) {
if (err) {
throw err;
}
username = results[0];
if (username && event_name)
writeReply(res, template, username, event_name);
});
// some non-blocking db query
query('SELECT name FROM events WHERE key=req.params['key']', function (err, results, fields) {
if (err) {
throw err;
}
event_name = results[0];
if (username && event_name)
writeReply(res, template, username, event_name);
});
};