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);
})
}