Javascript Fetch函数返回[object Promise]



我目前正在做一个项目,其中包括一个网站,由Django构建和运行。在这个网站上,我试图通过快速API加载数据,并尝试通过JavaScript和Fetch API加载此数据。但我总是得到的不是通过API提供的数据,而是一个[对象承诺]。我试过许多不同的方法,但似乎都不起作用。

我试过了,例如:

document.getElementById("1.1").innerHTML = fetch('the URL')
.then(response => response.text())

document.getElementById("1.1").innerHTML = fetch('the URL')
.then(response => response.text())
.then((response) => {
console.log(response)
})

和许多其他方法。我也检查了,API请求工作完美,返回一个字符串。

您希望在记录最终响应时显示html的设置,例如:

fetch('the URL')
.then(response => response.text())
.then((response) => {
console.log(response)
document.getElementById("1.1").innerHTML = response
})

其他方法包括使整个响应承诺实现:

const getData = async (url) => {
const res = await fetch(url)
const resText = await res.text()
return resText
}
const addTextFromUrl = async (url, element) => {
const text = await getData(url)
element.innerHtml = text
}
addTextFromUrl('theUrl', document.getElementById("1.1"))

一般来说,学习时遵循async/await语法更容易一些,但你应该总是尝试/捕获任何错误。

每个.then调用都返回一个新的promise。所以

你需要在回调中赋值或者使用async/await

fetch('the URL')
.then(response => response.text())
.then((response) => {
document.getElementById("1.1").innerHTML = response
})

或者在async函数中

async function getHtml() {
document.getElementById("1.1").innerHTML = await fetch('the URL')
.then(response => response.text())
}
getHtml();

W/o使用then

async function getHtml() {
const response = await fetch('the URL');
const html - await response.text();
document.getElementById("1.1").innerHTML = html;
}
getHtml();

相关内容

最新更新