Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

104
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda