I am having trouble with getting the contents of a text file. I basically have a file with around 8000 words which I would like to save into a string. But when I use the fetch() function and try to return the file's contents it gives me an undefined value.
Here's the function I made which ideally would return the file contents as a string.
function getValidWords() {
fetch("./words.txt")
.then((response) => response.text())
.then(function (textFile) {
return textFile;
});
}
And here I try to print it out.
let validWords = getValidWords();
console.log(validWords);
But when having the print statement there, outside the fetch().then() function it treats it as undefined But if I try printing inside the function like this it works perfectly fine.
function getValidWords() {
fetch("./words.txt")
.then((response) => response.text())
.then(function (textFile) {
console.log(textFile);
});
}
I know I can handle the file inside the function instead of the returning it and trying to manipulate it somewhere else. But the thing is that I need the contents of the file in multiple places and if feels unnecessary or redundant to be required to use it everytime i need to access the file. I also know it has something to do with promises and if I return it there's no guarantee the promise will hold.
My question is: Can I somehow manipulate the promise to always return the text file? Or should I be using something else and if so, what?