As Roamer-1888 added in the comments, async functions always return a Promise, even if you await
inside it and then return the data it will return as a Promise.
In the function's caller, you will have to await the Promise or use .then()
on it in order to access the delivered data.
The toJson
function could be better written to just return a Promise like this
function toJson (filepath) {
const file = fs.createReadStream(filepath)
return new Promise((resolve, reject) => {
Papa.parse(file, {
header: true,
complete (results, file) {
resolve(results.data)
},
error (err, file) {
reject(err)
}
})
})
}
Now when you call toJson()
, you can use either await
if you are inside of an async function or chain .then()
on the returned Promise to access the data.
async function main() {
try {
const data = await toJson(filepath)
// do something with the data...
} catch (err) {
console.error('Could not parse json', err)
}
}
Or with .then()
toJson('path')
.then(console.log)
.catch(console.log)
You will be able to catch errors from the underlaying FileReader (thanks to calling reject
inside the error
function). Keep in mind that by calling resolve
with results.data
you put aside results.errors
and results.meta
which contain useful information about the read csv.