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

216
Views
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 answers
Answer question

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 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!