如何从node.js中的函数外部访问局部变量

时间:2021-04-01 15:23:13

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.

我在这里尝试的只是访问函数外部的局部变量'htmlrows',但似乎用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?

能告诉我如何在函数外部访问'htmlrows'吗?

Thanks much in advance

非常感谢提前

1 个解决方案

#1


2  

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

你的问题是node.js是异步的,所以console.log(htmlrows);正在查询函数完成之前执行。

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:

您可以尝试使用node.js的异步中间件,这将允许您串联链接异步调用,以便它们按特定顺序执行:

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

#1


2  

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

你的问题是node.js是异步的,所以console.log(htmlrows);正在查询函数完成之前执行。

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:

您可以尝试使用node.js的异步中间件,这将允许您串联链接异步调用,以便它们按特定顺序执行:

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