【问题标题】:Reading a file's contents after fetching获取后读取文件的内容
【发布时间】:2020-08-23 03:25:03
【问题描述】:

导入具有适当标题名称的文件后,我正在尝试使用 .text() 方法读取内容。这些方法应该返回一个带有已解析数据的承诺。为什么我在 console.log(text) 时仍然得到“未定义”?

//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()}\n`);
  }
}

showTypes();

【问题讨论】:

    标签: javascript promise async-await fetch


    【解决方案1】:

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

    return response.text()
    

    response.text() 返回一个承诺。如果对then() 的回调结果是一个promise,那么链中的下一个then() 将使用新promise 的解析值调用。

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

    【讨论】:

      猜你喜欢
      • 2021-08-29
      • 2022-11-19
      • 2018-09-21
      • 2019-08-02
      • 2021-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-12
      相关资源
      最近更新 更多