0

For below function 'JSON OBJECT!' prints after 'JSON to CSV!' and the second print statement does not contain the json data. Please help.

    function _inputs() {

    let responseData:any = [];
    const csvFilePath='Data/output.csv'
    const csv=require('csvtojson')
    csv()
        .fromFile(csvFilePath)
        .then((jsonObj)=>{
            responseData.push(jsonObj);
            console.log('JSON OBJECT!' + JSON.stringify(responseData));
            responseData;
        });


    console.log('JSON to CSV! ' + responseData);
    return responseData;

};
SUM
  • 1,651
  • 4
  • 33
  • 57
  • 1
    It won't let me answer since this was marked as a duplicate, but odds are you're new to Promises and async/await will just make your life harder. Try using something like [CSV Parse's synchronous API](https://csv.js.org/parse/api/#sync-api) instead of `csvtojson` – stevendesu May 10 '19 at 18:01

1 Answers1

0

The problem is that

 console.log('JSON to CSV! ' + responseData);

is executed BEFORE

console.log('JSON OBJECT!' + JSON.stringify(responseData));

as the part within the then() is done asynchronously. The asynchronous process is started and then the rest of the code is executed immediately without waiting till the asynchronous code is computed. You have to do the processing in the then() block or you can use syntactic sugar with async/await:

async function _inputs() {

  const csvFilePath='Data/output.csv'
  const csv = require('csvtojson')
  const responseData = await csv()
    .fromFile(csvFilePath);
  console.log('JSON to CSV! ' + responseData);
  return responseData;
}
thopaw
  • 3,796
  • 2
  • 17
  • 24