Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

106
Views
Returning a JavaScript promise as a value

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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!