试图从API获取,但却获得了[object Promise]



我想做一个网站,从一首诗中取出随机的10行,然后在HTML文件中输出它们,而不是得到。json数据我得到[对象承诺]。有人能帮我一下吗?

下面是我的代码:

JS:

let url = 'https://poetrydb.org/random,linecount/1;10/title,author,lines.json'
const button = document.getElementById('button')
const body = document.getElementById('poem')
async function requestPoem(url) {
await fetch(url)
.then((response)=>{
let data = response.json()
return data
})
}
button.onclick = ()=>{
body.innerHTML = requestPoem(url)
}

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script defer src="scripts/main.js"></script>
<title>poem request</title>
</head>
<body>
<p id="poem"></p>
<button id="button">request poem</button>
</body>
</html>

requestPoemasync函数,因此它只能返回一个promise。你不能避免这个承诺,但是你可以使用它,要么调用.then,要么把你的代码放在async函数中,然后使用await。此外,您当前的requestPoem函数没有返回语句,因此它需要一个来定义承诺解析到什么。

async function requestPoem(url) {
const response = await fetch(url);
return response.json();
}
button.onclick = async () => {
body.innerHTML = await requestPoem(url);
}

原来代码中的错误是API返回了一个对象数组而不是单个对象。因此,我首先必须返回data[0]并从中获取对象的属性。

相关内容

最新更新