[英]Node.js: How can i store the jsonObj in a global variable after converting CSV to JSON by using csvtojson
I want to store the jsonObj in a global variable. 我想将jsonObj存储在全局变量中。 However, it doesn't work.
但是,它不起作用。
var jsonContent;
csvConverter.on("end_parsed", function(jsonObj){
// console.log(jsonObj);
jsonContent = jsonObj;
});
console.log(jsonContent);
jsonObj can be printed correctly inside {...}. jsonObj可以在{...}内部正确打印。 But why can't I pass it to a global variable?
但是为什么不能将其传递给全局变量? The result of "console.log(jsonContent);"
“ console.log(jsonContent);”的结果 is still undefined.
仍未定义。
undefined
jsonContent
is global in the sense that it is available everywhere in your JS file. jsonContent
是全局的,因为它在JS文件中的任何位置都可用。 The problem is that csvConverter.on
is asynchronous , so it will not block the program while it runs. 问题是
csvConverter.on
是异步的 ,因此它在运行时不会阻塞程序。 Therefore, you will not be able to use jsonContent
until after csvConverter.on
runs its callback. 因此,直到
csvConverter.on
运行其回调之后,您才能使用jsonContent
。
If you need to use jsonObj
, you have to use it after your callback to csvConcerter
runs. 如果需要使用
jsonObj
,则必须在对csvConcerter
的回调运行后使用它。 In order to do so, you can simply wrap your logic in a function and run that function once your callback is called: 为此,您可以简单地将逻辑包装在一个函数中,并在调用回调后运行该函数:
var jsonContent;
csvConverter.on("end_parsed", function(jsonObj){
jsonContent = jsonObj;
runLogic();
});
function runLogic() {
// this function will run after csvConverter.on callback is called
console.log(jsonContent);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.