嘿,我目前正在学习promises如何通过使用异步函数从API接收的对象加载我的本地存储,代码实际上有效,但是当我尝试遍历数组时,我遇到了问题我使用响应对象创建,我有两个按钮逐个循环遍历数组元素,但除非重新加载页面,否则它们不起作用,如果我检查我的控制台,我可以看到本地存储中的对象,这个错误弹出:
Uncaught TypeError: Cannot read property 'length' of null
at Object.nextJoke (bundle.js:10332)
at HTMLDivElement.jokeContainer.addEventListener.event
。
我目前的代码是:
JS ::
const jokeContainer = document.querySelector('.joke-container');
const jokesArray = JSON.parse(localStorage.getItem('jokesData'));
// Fetch joke count from API endpoint
async function sizeJokesArray() {
let url = 'https://api.icndb.com/jokes/count';
let data = await (await fetch(url)).json();
data = data.value;
return data;
}
// use API endpoint to fetch the jokes and store it in an array
async function fetchJokes() {
let url = `https://api.icndb.com/jokes/random/${length}`;
let jokesData = [];
let data = await (await fetch(url)).json();
data = data.value;
for (jokePosition in data) {
jokesData.push(data[jokePosition].joke);
}
return localStorage.setItem('jokesData', JSON.stringify(jokesData));
}
if (jokesArray === null) {
sizeJokesArray()
.then(size => (length = size)) // Size of array in response
.then(fetchJokes);
}
const jokeDispenser = (function() {
let counter = 0; //start counter at position 0 of jokes array
function _change(position) {
counter += position;
}
return {
nextJoke: function() {
_change(1);
counter %= jokesArray.length; // start from 0 if we get to the end of the array
return jokesArray[counter];
},
prevJoke: function() {
if (counter === 0) {
counter = jokesArray.length; // place our counter at the end of the array
}
_change(-1);
return jokesArray[counter];
}
};
})();
// pass selected joke to print on html element
function printJoke(joke) {
document.querySelector('.joke-text p').textContent = joke;
}
jokeContainer.addEventListener('click', event => {
if (event.target.value === 'Next') {
printJoke(jokeDispenser.prevJoke(jokesArray));
} else if (event.target.value === 'Prev') {
printJoke(jokeDispenser.nextJoke(jokesArray));
}
});
HTML ::
<body>
<div class="joke-container">
<div class="joke-text">
<p>Fetch some jokes bro!!</p>
</div>
<div class="joke-controls">
<button type="button" value="Prev">Prev</button>
<button type="button" value="Next">Next</button>
</div>
</div>
</body>
我知道我的问题与我的承诺链接或作曲有关但在阅读Google Promises之后 和MDN Promises我真的没有办法解决这个问题。