user3747813
user3747813

Reputation: 11

How to access a local variable from outside the function in node.js

All I am trying here is to access the local variable 'htmlrows' outside the function but it seems its not that easy with node.js.

var htmlrows;
query.on('row', function(row) {    
  console.log("%s  |%s |%d",    row.empid,row.name,row.age); 
  htmlrows += "<tr><td>" + row.empid + "</td><td>" +row.name + "</td><td>" +row.age + "</td></tr>";

});

console.log("htmlrows outside function");
console.log(htmlrows); // console log prints 'undefined'.

Could you please let me know how to access 'htmlrows' outside the function?

Thanks much in advance

Upvotes: 1

Views: 2296

Answers (1)

Stephen Wright
Stephen Wright

Reputation: 2956

Your issue is that node.js is asynchronous, so console.log(htmlrows); is being executed before the query function has completed.

What you need to do is have a separate function that listens for a callback from the query function.

You could try using the async middleware for node.js, which will allow you to chain async calls in series, so that they get executed in a certain order:

var some_data = null;
async.series([
    function(callback) {
      //...do a thing
      function_1(callback);
    },
    function(callback) {
      //...do another thing
      function_2(callback);
    }
    //...etc
]);

function function_1(callback) {
    some_data = 'value';
    console.log('function_1!');
    return callback();
}

function function_2(callback) {
    console.log('function_2: '+some_data);
    return callback();
}

will result in:

#:~ function_1!
#:~ function_2: value

Upvotes: 3

Related Questions