【发布时间】:2022-01-22 10:13:22
【问题描述】:
我正在构建一个简单的应用程序,它可以访问 API 并呈现信息。它由按钮中的事件侦听器激活,该侦听器获取 html 输入字段的值并将其插入到我的 apiCall 函数中。然后我的代码处理 api 响应并将所需的数据分配给对象内部的变量,然后 console.log'ged out。
这是我的问题:当我第一次单击按钮时,我收到以下错误消息:
Uncaught TypeError: Cannot read properties of undefined (reading 'average_price')
at Object.getAveragePrice (index.js:17)
at render (index.js:27)
at HTMLButtonElement.<anonymous> (index.js:33)
然后我第二次单击该按钮,我在控制台中获得了正确的数据。我究竟做错了什么?下面是我的javascript。
let jsonResponse = ""
let collectionName = ""
let inputEl = document.getElementById("input-el")
let buttonEl = document.getElementById("button-el")
function callApi(collectionName) {
fetch(`https://api.opensea.io/api/v1/collection/${collectionName}/stats`)
.then(response => response.json())
.then(response => jsonResponse = response)
.catch(err => console.error(err));
}
const getJsonData = {
getAveragePrice: function() {
collectionData.averagePrice = jsonResponse.stats["average_price"]
}
}
let collectionData = {
averagePrice: ""
}
function render() {
callApi(collectionName)
getJsonData.getAveragePrice()
console.log(JSON.stringify(collectionData.averagePrice))
}
buttonEl.addEventListener("click", () => {
collectionName = inputEl.value
render()
})
【问题讨论】:
-
因为您正在调用异步函数,然后尝试在它有机会完成之前访问它的结果。有很多关于此的 SO 帖子
标签: javascript html json api