1

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

3
  • Why not apply the logic inside the function, where the result is returned? Commented Jun 17, 2014 at 9:52
  • Thanks Ben for the quick response. As you said rightly that is a possibility but I would like to access is outside the function.Just for my learning if I really wanted to access outside the function how would i do it? Commented Jun 17, 2014 at 10:03
  • Assuming there's an end event in the instance of EventEmitter which is query (this is typical): query.on('row',function(row){...htmlrows += "...";}).on('end',function(){console.log(htmlrows);}); Commented Jun 17, 2014 at 10:07

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.