【发布时间】: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