在使用适当的头文件名导入文件后,我尝试使用.text()方法读取内容。这些方法应该返回一个包含已解析数据的promise。为什么当我console.log(文本)的时候我仍然是“未定义的”?
//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();发布于 2020-05-08 01:54:21
在第一个代码块中,需要返回response.text()
return response.text()response.text()返回一个promise。如果对then()的回调结果是promise,那么将使用新promise的解析值调用链中的下一个then()。
现在,您的第一个then处理程序不返回任何内容(undefined),因此该值也将传递给链中的下一个promise。
https://stackoverflow.com/questions/61664450
复制相似问题