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

211
Vistas
How to return a file fetched with promise in JavaScript?

What I have tried is this:

function getEventFileFromServer () {
  const fetchedPromise = fetch('event-file.txt');
  fetchedPromise.then(eventFile => eventFile.text())
  .then(contentOfEventFile => {
    return contentOfEventFile;
  });
}

console.log(getEventFileFromServer()) // logs 'undefined'

If I do console.log(contentOfEventFile) instead of return contentOfEventFile, I can see the content of the file in the console, but I how can I return it to use it in a different function?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The problem is the fact that fetching the file is an asynchronous event and the function returned undefined before your promise resolves. Consider it like this -

function getEventFileFromServer () {
  const fetchedPromise = fetch('event-file.txt');
  fetchedPromise.then(eventFile => eventFile.text())
  .then(contentOfEventFile => {
    return contentOfEventFile;
  });
  return undefined;
}

Now, you have couple of options.

1.) Async/Await

async function getEventFileFromServer () {
  const eventFile = await fetch('event-file.txt');
  const contentOfFile = await eventFile.text();
  return contentOfFile;
}

then use it wherever you want with async/await or promise i.e. -

async useFileValue() {
    const data = await getEventFileFromServer();
    console.log(data);
}

2.) Returning the promise itself -

Instead of using .then on the promise, simply return the promise i.e. -

function getFileEvent() {
     return fetch('event-file.txt');
}

and now get the value resolved by promise wherever you want by using .then

function getFileData() {
    getFileEvent().then(eventFile => eventFile.text())
                  .then(contentOfEventFile => {
                      // Do whatever you want with data here
                      console.log(contentOfEventFile);
                  })
}
about 4 years ago · Juan Pablo Isaza Denunciar
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