I have been given the task of reading a file, processing the data and returning the results. As it is an async process, I run into the problem where you cannot return from a .then, and an unresolved Promise is unresolved. I am using fetch. I know this issue has been discussed a lot, apologies. Here is code. Thank you.
function myFunction () {
async function fetchData() {
await fetch("./my_file.txt")
.then((res) => res.text())
.then((text) => {
//I want to return text here
})
.catch((e) => console.error(e));
}
const response = fetchData();
//I can process the data here and then return it
//process data
//return results
}
2
Answers
Try something like this:
You cannot immediately return the results, that is just impossible. You can always only return a promise for them, no matter how you write it.
The easiest is to just
return
the chained promise:You can also use
async
/await
instead of.then()
:Notice I’ve removed the
.catch(e => console.error(e))
part from both. That should be done only by the caller ofmyFunction()
. Or if you don’t return a result anywhere, e.g.