I've tried every different version I can find to try to extract the text from fetching a file and save it to a variable to be accessed outside of the async function used to fetch it, but I just can't figure out what I'm doing wrong. I know the fetch
is working because I can get the file data to print from inside the function. The current version of one of my attempts looks like this:
async function getData(filePath) {
await fetch(filePath)
.then(response => {
return response.text()
})
.then(data => alert(data))
.catch(error => alert(error))
}
alert(getData('./2021WeatherData.csv'))
This first creates two alerts (can't figure out why everything is happening multiple times but I'll worry about that later) that read "[object Promise]", and then two more with the actual file contents. So I know the async function is returning a Promise and I know I am able to extract the text from the file within the function.
This question/solution (async/await implicitly returns promise?) tells me the result of an async function is always a Promise even if within the function you return a string, number, etc. I've tried throwing .text()
onto the end, but when I do that I get "TypeError: getData(...).text is not a function".
One thing I can't wrap my head around is why the alert associated with alert(getData('./2021WeatherData.csv'))
occurring before the alert for .then(data => alert(data))
. It seems getData would need to complete its course to return
the Promise object to the getData call alert
and in the process would trigger the internal .then(data => alert(data))
prior to doing that. I don't know if this is relevant because one of my attempted methods was to create a global variable outside of the async function like so:
let theData = 'blank'
const getData = async function (filePath) {
fetch(filePath)
.then(response => response.text())
.then(response => {
theData = response
alert(theData)
return theData
})
}
alert(getData('./2021WeatherData.csv'))
alert(theData)
Here, the alert for alert(getData('./2021WeatherData.csv'))
pops up first as "[object Promise", followed by alert(theData)
providing the default value of "blank" it was initialized with, and then finally alert(response)
within the function provides the actual file contents. Very much the same as without the global variable. I just can't figure out why the execution is moving from the getData call down to the alert(theData)
execution before completing the run through the function and updating theData.
I know I'm showing how little I know about async/await, promises, etc. I'm just at my wits end and don't know what to do. Thank you in advance.