首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Node.js csvtojson -在函数外部返回结果

Node.js csvtojson -在函数外部返回结果
EN

Stack Overflow用户
提问于 2018-06-22 22:44:32
回答 1查看 524关注 0票数 1

我对此相对比较陌生,还不太清楚这一切是如何工作的……

基本上,我使用csvtojson函数将csv文件转换为json。这可以很好地工作,并将json数组输出到console.log。

执行此操作后,我想获取返回的json数组,并对其执行一些额外的操作,例如输出到文件。

我的问题是如何在创建数组的函数之外使用它,或者我是否应该在函数内编写代码?

这是我的代码:

代码语言:javascript
复制
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

有人能帮我理解一下我需要做什么吗?

EN

回答 1

Stack Overflow用户

发布于 2018-06-22 22:53:06

因为csv()函数是异步的,并且返回一个Promise对象。您可以在.then()函数中读取值。

解释器查看代码的方式:

代码语言:javascript
复制
// 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

过了一段时间

代码语言:javascript
复制
// Execute the .then function
.then((jsonObj)=>{
   // Display the content of the variable jsonObj
   console.log(jsonObj);
});

这里的是一个演示代码片段

代码语言:javascript
复制
const asynchronousFunction = () => new Promise((resolve) =>
  setTimeout(() => resolve('asynchronous'), 1000));

const ret = 'not initialized';

asynchronousFunction()
  .then((ret) => {
    console.log(ret);
  });

console.log(ret);

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50990456

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档