EDIT: Someone has marked this question as closed because there are already answers on other similar questions. However, none of the other questions provide a solution to my question.
I am struggling with this seemingly most basic task. I have an async function asyncFunc() that reads a file, but for simplicity let's say this function returns "Hello world". I run the following code in my app.js top-level file.
console.log('Getting mydata...')
mydata = asyncFunc()
console.log('My data is', mydata)
process.exit()
When I run this the output is
Getting mydata...
mydata is Promise {[[PromiseState]]: 'pending'
The output that I want is:
Getting mydata...
mydata is Hello World
I have tried following the suggestion of @splichte in this github post about the issue and using the code below. But I get the same incorrect output as before. https://github.com/Keyang/node-csvtojson/issues/278
async function run() {
const data = await asyncFunc();
return data
}
console.log('Getting mydata...')
mydata = run()
console.log('My data is', mydata)
//continue with rest of my program
//many sections of which will use mydata
process.exit()
I have tried the suggestion of using myData = await run()
but this gives the error
await is only valid in async functions and the top level bodies of modules
Can someone please post some example code to get the desired output below?
Getting mydata...
mydata is Hello World