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

210
Views
¿Cómo devolver un archivo obtenido con promesa en JavaScript?

Lo que he probado es esto:

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

Si hago console.log(contentOfEventFile) en lugar de return contentOfEventFile , puedo ver el contenido del archivo en la consola, pero ¿cómo puedo devolverlo para usarlo en una función diferente?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

El problema es el hecho de que obtener el archivo es un evento asíncrono y la función se devolvió indefinida antes de que se resuelva su promesa. Considéralo así:

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

Ahora, tienes un par de opciones.

1.) Asíncrono/Espera

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

luego úsalo donde quieras con async/await o promise, es decir, -

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

2.) Devolver la promesa misma -

En lugar de usar .then en la promesa, simplemente devuelva la promesa, es decir:

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

y ahora obtenga el valor resuelto por promesa donde quiera usando .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 Report
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!