0

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?

yendrrek
  • 191
  • 2
  • 12

1 Answers1

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);
                  })
}
Pawan Sharma
  • 1,842
  • 1
  • 14
  • 18