如何从事件触发时调用的函数更改全局变量?

时间:2022-01-23 19:23:06

Using NodeJS and node-csv, I'm trying to load rows in a Array. From an example in the module:

使用NodeJS和node-csv,我正在尝试加载数组中的行。从模块中的示例:

// node samples/string.js
csv()
    .from.string(
        '#Welcome\n"1","2","3","4"\n"a","b","c","d"', {
            comment: '#'
        })
    .to.array(function (data) {
        console.log(data)
    });
// [ [ '1', '2', '3', '4' ], [ 'a', 'b', 'c', 'd' ] ]

But if inside function (data) I try to add each row to an Array defined in the global scope, it doesn't alter it. It's obvious I don't understand JS variables scope, but what's the best pattern to solve this problem?

但是如果在函数内部(数据)我尝试将每一行添加到全局范围中定义的数组,它不会改变它。很明显我不了解JS变量范围,但解决这个问题的最佳模式是什么?

1 个解决方案

#1


1  

It looks like it is altering the rows variable, but the console.log() call is being called before the rows are pushed. You can use the .on('end') event to call a function after they have been pushed.

看起来它正在改变行变量,但是在推送行之前调用了console.log()调用。您可以使用.on('end')事件在推送后调用函数。

var csv = require('csv');
var rows = new Array();


csv()
    .from.string(
        '#Welcome\n"1","2","3","4"\n"a","b","c","d"', {
            comment: '#'
        })
    .to.array(function (data) {
    rows.push(data);
        console.log(rows);
    }).on('end', function() {
        logRows();
    });

var logRows = function() {
    console.log(rows);
}

#1


1  

It looks like it is altering the rows variable, but the console.log() call is being called before the rows are pushed. You can use the .on('end') event to call a function after they have been pushed.

看起来它正在改变行变量,但是在推送行之前调用了console.log()调用。您可以使用.on('end')事件在推送后调用函数。

var csv = require('csv');
var rows = new Array();


csv()
    .from.string(
        '#Welcome\n"1","2","3","4"\n"a","b","c","d"', {
            comment: '#'
        })
    .to.array(function (data) {
    rows.push(data);
        console.log(rows);
    }).on('end', function() {
        logRows();
    });

var logRows = function() {
    console.log(rows);
}