Click here to Skip to main content
15,893,486 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I’m using the csvtojson library to convert a csv to a json object and then push to an array. However, when I console.log(data) the array, it is empty but when I console.log(data) in csv({}) it does show the array with the jsonobj inside.

Thanks so much!

What I have tried:

I've tried using async/await function but I'm still having trouble saving the data.
const csvFilePath = 'myCsv.csv'; 
let data = [];
async function convertCsv(csvData) {
    const jsonArray= await csv({noheader: true, headers: headers}).fromFile(csvData).on('json', (jsonObj) => { 
    
        data.push(jsonObj); // Push each object to data Array
        console.log('data',data);
        
    })
    return jsonArray;
}

async function run() {
    let dat = await convertCsv(csvFilePath).then(dat => data.push(dat))
    return dat;
  }
  
  run()
console.log(data);
Posted
Updated 11-Nov-20 23:39pm

1 solution

Quote:
JavaScript
async function run() { ... }

run();
console.log(data);
You're logging the data before the function has finished executing.
async function - JavaScript | MDN[^]

You need to wait for the function to finish before you can access its output. The simplest way to do that is to move your console.log line inside the async function:
JavaScript
async function run(){
    let dat = await convertCsv(csvFilePath);
    data.push(dat);
    console.log(data);
    return dat;
}

run();
 
Share this answer
 
Comments
ynjay 12-Nov-20 9:17am    
Thanks so much! Is there a way to save the data into a variable outside the function so I can use it in other parts of the code?
Richard Deeming 12-Nov-20 11:55am    
You're already doing that. But you can't access the data before it is assigned, which means you need to wait for the async function to finish running first.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900