简体   繁体   English

Javascript 使用异步加载本地 .txt 文件

[英]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.我正在尝试使用 async 函数在与我的项目相同的目录中加载 .txt 文件,但我在 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: text.txt 文件包含:

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. res是一个Response对象。 If you want the text of it, call .text()如果你想要它的文本,调用.text()

    fetch(file).then(function(res){
       return res.text(); // change here
    }).then(function(resp){
       return resp; // your content here
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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