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
5
  • fetch() resolves to a Response object, whose .body property exposes methods that let you (asynchronously) read the contents of the file. developer.mozilla.org/en-US/docs/Web/API/Fetch_API Commented May 7, 2018 at 14:25
  • @Leon I can't see the contents that are in the .txt file. Commented May 7, 2018 at 14:26
  • duplicate of stackoverflow.com/questions/40385133/… Commented May 7, 2018 at 14:28
  • @mplungjan Daniel's answer below solved my issue. I was missing the .text() after the first return. Commented May 7, 2018 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. Commented May 7, 2018 at 14:37

1 Answer 1

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
    });
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome! I was missing the .text() after the first return. Thanks Daniel.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.