尝试从API获取,但要获得[对象承诺]
我正在尝试制作一个网站,该网站从诗中获取10行,然后在HTML文件中输出它们,而不是获取我得到的.json数据[Object Promise]。有人可以帮我吗?
这是我的代码:
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>
I'm trying to make a website that fetches a random 10 lines from a poem and then outputs them in the HTML file but instead of getting the .json data I'm getting [object Promise]. Can someone help me out?
Here's my code:
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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
requestPoem
是async
函数,因此它只能返回承诺。您无法避免承诺,但是可以通过调用。
结果。另外,您当前的requestPoem
函数没有返回语句,因此需要一个来定义承诺的决心。requestPoem
is anasync
function, so it can only ever return a promise. You can't avoid the promise, but you can use it, either by calling.then
on it, or by putting your code in anasync
function andawait
ing the result. Also, your currentrequestPoem
function has no return statement, so it will need one to define what the promise resolves to.事实证明,代码中的错误是API返回了一个对象而不是一个对象。因此,我首先必须返回数据[0]并从那里获取对象的属性。
Turns out the mistake in the code was that the API was returning an array of objects instead of a single object. Because of this I first had to return data[0] and get the object's properties from there.