[提取后读取文件的内容

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[提取后读取文件的内容相关的知识,希望对你有一定的参考价值。

导入具有适当标题名称的文件后,我尝试使用.text()方法读取内容。该方法应返回已解决数据的承诺。当我console.log(text)时,为什么仍然会出现“ undefined”?

//fetch the three forms
let headerArr = ['text/html', "text/plain", "application/json","application/rainbows+unicorns"]

for (let type of headerArr){

  fetch("https://eloquentjavascript.net/author" , {headers: {'Accept': type}})
    .then(response => {
      console.log(response.headers.get("Content-Type"));
      console.log(response.status);
      response.text();
      })
    .then(text=> console.log(text));

}

下面是Eloquent JavaScript这本书的另一种替代方法。相反,他们使用了异步方法而不是then / catch。他们得到了预期的结果。这是怎么回事?

const url = "https://eloquentjavascript.net/author";
const types = ["text/plain",
               "text/html",
               "application/json",
               "application/rainbows+unicorns"];

async function showTypes() {
  for (let type of types) {
    let resp = await fetch(url, {headers: {accept: type}});
    console.log(`${type}: ${await resp.text()}
`);
  }
}

showTypes();
答案

在您的第一个方框中,您需要返回response.text()

return response.text()

response.text()返回一个承诺。如果回调到then()的结果是一个Promise,则将使用该新Promise的解析值来调用链中的下一个then()

现在,您的第一个then处理程序将不返回任何内容(undefined),因此该值也将传递给链中的下一个promise。

以上是关于[提取后读取文件的内容的主要内容,如果未能解决你的问题,请参考以下文章