简体   繁体   中英

Javascript using async to load local .txt file

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM