0

I want to read a TXT file from a directory, I have this code which works fine

window.onload = () => {
  fetch("file.txt")
    .then(res => res.text())
    .then(data => {
      console.log(data);
    });
};

But I want to exe the fetch call in a function like so:

window.onload = () => {
  const filePath = "file.txt";
  const fileData = readDataFile(filePath);
  console.log(fileData);
};

const readDataFile = path => {
  fetch(path)
    .then(res => res.text())
    .then(data => {
      return data;
    });
};

But in this case, it returns undefined.

Another problem with it, is I can't catch if an error occurs, I tried adding catch to the promise and throw an error but it does not work. This is what I've tried:

window.onload = () => {
  fetch("file.txt")
    .then(res => res.text())
    .then(data => {
      console.log(data);
    })
    .catch(err => {
      throw new Error("ERROR!");
    });
};

THANKS :)

This works:

const readDataFile = async path => {
    try {
        const response = await fetch(path);
        const data = await response.text();
        return data;
    } catch (err) {
        console.log('Cannot read file.');
    }
}

window.onload = async () => {
    const filePath = 'data.txt';
    const fileData = await readDataFile(filePath);
    console.log(fileData);
}

But again, the catch method does not work ? am I doing it wrong ?

user12499410
  • 392
  • 5
  • 17
  • 3
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Ivar Jul 06 '20 at 11:53
  • I tried `async` `await` and failed.. – user12499410 Jul 06 '20 at 12:05

0 Answers0