So say I've got a function:
function grabOldestJob() {
var client = mysql.createClient({
user: dbConfig['USER'],
password: dbConfig['PASS'],
});
client.query('USE '+dbConfig['DATABASE']);
client.query('SELECT url FROM '+dbConfig['JOB_TABLE']+' ORDER BY added ASC LIMIT 1 ',
function selectCb(err, results, fields, passed) {
if (err) {
throw err;
}
client.end();
fetchFeed(results[0]['url']);
}
);
}
What I need is the results[0]['url'] buried in the inline function, so either I'd like to get that variable out of that function so I can use it to return the grabOldestJob function or pass another function into the inline function so I can use results[0]['url'] as a parameter.
I'm very new to the concepts of node.js and would like to make my code as 'proper' as possible. This function is the first in a process, it pulls a url out of a database, passes that to get fetched from the remote server, the xml feed gets parsed and certain bits get stored in a database. I'm hoping using the ability of node to 'run lots of things at once' I'll be able to fetch->parse->save many feeds at the same time. Any best practice tips for this would also be greatly appreciated.
Use callback functions for this.
Like the client.query(query,callback)
function does. You pass in the data and a callback function that gets called if the processing completed. Do the same with your fetchFeed(url,callback)
function.
...
client.end();
fetchFeed(results[0]['url'],function(result){
// here 'result' contains the fetched feed and can be stored into the database
});
...
function fetchFeed(url,cb){
// download feed here and call cb(downloaded_data) when finished, passing the downloaded data to the cb() function
}
Have a look at: Understanding the node.js event loop
Each variable defined in an outer scope is visible in the inner scope of the outer scope. That basically means that when you define variable in a function with keyword 'var', it's going to be visible to any nested function. On the other hand when you define a variable without the 'var' keyword, it's going to be visible in the global scope. Here's an example:
(function () {
var v = 5;
(function () {
v = 3;
})();
console.log(v);
})();
This will print out 3. So if you want an argument to be visible outside the inner function you have to copy it (not sure about referencing as the variable will probably going to be garbage collected?) into a global variable. Like this
(function () {
var v = 5;
(function (n) {
v = n;
})(42);
console.log(v);
})();
and this will print out 42.