title: JS read file onload returns undefined
body: <p>I want to read a TXT file from a directory, I have this code which works fine</p>
  <pre class="lang-js prettyprint-override"><code>window.onload = () =&gt; {
    fetch(&quot;file.txt&quot;)
      .then(res =&gt; res.text())
      .then(data =&gt; {
        console.log(data);
      });
  };
  </code></pre>
  <p>But I want to exe the fetch call in a function like so:</p>
  <pre class="lang-js prettyprint-override"><code>window.onload = () =&gt; {
    const filePath = &quot;file.txt&quot;;
    const fileData = readDataFile(filePath);
    console.log(fileData);
  };
  
  const readDataFile = path =&gt; {
    fetch(path)
      .then(res =&gt; res.text())
      .then(data =&gt; {
        return data;
      });
  };
  </code></pre>
  <p>But in this case, it returns <code>undefined</code>.</p>
  <p>Another problem with it, is I can't catch if an error occurs, I tried adding <code>catch</code> to the promise and <code>throw</code> an error but it does not work. This is what I've tried:</p>
  <pre class="lang-js prettyprint-override"><code>window.onload = () =&gt; {
    fetch(&quot;file.txt&quot;)
      .then(res =&gt; res.text())
      .then(data =&gt; {
        console.log(data);
      })
      .catch(err =&gt; {
        throw new Error(&quot;ERROR!&quot;);
      });
  };
  </code></pre>
  <h2>THANKS :)</h2>
  <p>This works:</p>
  <pre><code>const readDataFile = async path =&gt; {
      try {
          const response = await fetch(path);
          const data = await response.text();
          return data;
      } catch (err) {
          console.log('Cannot read file.');
      }
  }
  
  window.onload = async () =&gt; {
      const filePath = 'data.txt';
      const fileData = await readDataFile(filePath);
      console.log(fileData);
  }
  </code></pre>
  <p>But again, the catch method does not work ? am I doing it wrong ?</p>