【问题标题】:Javascript using async to load local .txt fileJavascript 使用异步加载本地 .txt 文件
【发布时间】:2018-10-17 09:31:00
【问题描述】:

我正在尝试使用异步函数将 .txt 文件加载到与我的项目相同的目录中,但我在 console.log 中看不到响应(文件的实际内容)。

我错过了什么?

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

text.txt 文件包含:

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

这是日志:

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

【问题讨论】:

  • fetch() 解析为Response 对象,其.body 属性公开了允许您(异步)读取文件内容的方法。 developer.mozilla.org/en-US/docs/Web/API/Fetch_API
  • @Leon 我看不到 .txt 文件中的内容。
  • @mplungjan Daniel 下面的回答解决了我的问题。第一次返回后我错过了 .text() 。
  • 不,我把错误留在那里。我刚刚在调试过程中犯了另一个愚蠢的错误,忘记了回到我的实际问题。上面的代码是我最初的问题。

标签: javascript function asynchronous fetch-api


【解决方案1】:

res 是一个 Response 对象。如果你想要它的文字,请致电.text()

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

【讨论】:

  • 太棒了!第一次返回后我错过了 .text() 。谢谢丹尼尔。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-09
  • 2012-11-24
  • 2012-10-11
相关资源
最近更新 更多