我对此相对比较陌生,还不太清楚这一切是如何工作的……
基本上,我使用csvtojson函数将csv文件转换为json。这可以很好地工作,并将json数组输出到console.log。
执行此操作后,我想获取返回的json数组,并对其执行一些额外的操作,例如输出到文件。
我的问题是如何在创建数组的函数之外使用它,或者我是否应该在函数内编写代码?
这是我的代码:
const csvFilePath='./test.csv'
const csv=require('csvtojson')
csv()
.fromFile(csvFilePath)
.then((jsonObj)=>{
console.log(jsonObj);
//should I write code here
});
console.log(jsonObj);
//This returns jsonObj is not defined
//how do I/Can I read jsonObj here
有人能帮我理解一下我需要做什么吗?
发布于 2018-06-22 22:53:06
因为csv()函数是异步的,并且返回一个Promise对象。您可以在.then()函数中读取值。
解释器查看代码的方式:
// Create a variable and store a data inside
const csvFilePath='./test.csv'
// Create a variable and store a data inside
const csv=require('csvtojson')
// Call the function csv().fromFile(csvFilePath), because it's asynchronous
// deal with the result later
csv()
.fromFile(csvFilePath)
.then((jsonObj)=>{
console.log(jsonObj);
});
// Display the content of the variable jsonObj
// jsonObj is not declared, display 'undefined'
console.log(jsonObj);
// Leave the current function过了一段时间
// Execute the .then function
.then((jsonObj)=>{
// Display the content of the variable jsonObj
console.log(jsonObj);
});这里的是一个演示代码片段
const asynchronousFunction = () => new Promise((resolve) =>
setTimeout(() => resolve('asynchronous'), 1000));
const ret = 'not initialized';
asynchronousFunction()
.then((ret) => {
console.log(ret);
});
console.log(ret);
https://stackoverflow.com/questions/50990456
复制相似问题