0

I am trying to use async function to load a .txt file in the same dir as my project, but I can't see the response (the actual content of the file) in the console.log.

What am I missing?

  async function myFunct(file){
     try {
        fetch(file).then(function(res){
           return res;
        }).then(function(resp){
           console.log (resp);
        });
     } catch(e) {
        console.log("The Error: " + e);
     } finally {

     }
  }

  myFunct('./text.txt');

The text.txt file contains:

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempora vero repudiandae dicta maxime quos temporibus labore exercitationem.

Here is the log:

Response {type: "basic", url: "http://{project_path}/text.txt", redirected: false, status: 200, ok: true, …}
body:ReadableStream
locked:false
__proto__:Object
bodyUsed:false
headers:Headers {}
ok:true
redirected:false
status:200
statusText:"OK"
type:"basic"
url:"{project_path}/text.txt"
__proto__:Response
Sergio
  • 792
  • 3
  • 10
  • 35
  • `fetch()` resolves to a `Response` object, whose `.body` property exposes methods that let you (asynchronously) read the contents of the file. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API – Máté Safranka May 07 '18 at 14:25
  • @Leon I can't see the contents that are in the .txt file. – Sergio May 07 '18 at 14:26
  • duplicate of https://stackoverflow.com/questions/40385133/retrieve-data-from-a-readablestream-object – Leon May 07 '18 at 14:28
  • @mplungjan Daniel's answer below solved my issue. I was missing the .text() after the first return. – Sergio May 07 '18 at 14:35
  • No I left the mistake there. I just made ANOTHER silly mistake in my debugging process and forgot to revert to my actual problem. The above code was my initial problem. – Sergio May 07 '18 at 14:37

1 Answers1

4

res is a Response object. If you want the text of it, call .text()

    fetch(file).then(function(res){
       return res.text(); // change here
    }).then(function(resp){
       return resp; // your content here
    });
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445