I have a Node.js application with asynchronous code like this:
var localvar1 = ...;
var localvar2 = ...;
var localvar3 = ...;
// do async database query
conn.query("select ...", function(err, res) {
// fetch results asynchronously
res.fetchAll(function(err, rows) {
if (rows.length == 0) // no, data, fetch from external HTTP source
{
// fetch from Internet asynchronously
https.get(..., function() {
// ok, got it, now save
// I need values from original function here ***
saveData(localvar1, localvar2, localvar3);
});
}
});
);
What is the best way to pass values of localvar1-3 to innermost function?
If you suggest some library for this, please provide example code that would work with the code I wrote above.
Thanks to closures, inner functions have access to local variables defined in outer functions or in the module itself, so your code as written will work if localvar1
, et.al., don't get changed while waiting for your https.get()
callback to be called. If they do get changed, your callback will see their new values, not the values they had at the time of the request. If that's a problem, create a new closure to "trap" them:
https.get(..., (function(arg1, arg2, arg3) {
return function() {
saveData(arg1, arg2, arg3);
}
})(localvar1, localvar2, localvar3));