我正在努力进行function
调用,当我从if
语句中调用该函数时它确实有效,但是当我从外部调用它时它没有,我的{{1} }语句只检查按下了哪个按钮,但我试图从按钮中删除该功能,只要我的应用程序启动就立即调用它。
我们会查看if
fetchJokes()
这是我目前的代码:
jokeContainer.addEventListener('click', event => {
我正在尝试这样做:
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));;
}
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;
}
sizeJokesArray().then(size => (length = size)); // Size of array in response
jokeContainer.addEventListener('click', event => {
if (event.target.value === 'Fetch') {
fetchJokes(length);
} else if (event.target.value === 'Next') {
printJoke(jokeDispenser.prevJoke(jokesArray));
} else if (event.target.value === 'Prev') {
printJoke(jokeDispenser.nextJoke(jokesArray));
}
});
顺便说一句,我知道目前,你不能使用prev和next按钮迭代数组元素而不刷新页面,但我猜这将是另一个问题。
想不出一个更好的头衔。(编辑欢迎)
答案 0 :(得分:2)
异步函数顾名思义就是异步。在
sizeJokesArray().then(size => (length = size)); // Size of array in response
fetchJokes(length);
您在执行 fetchJokes
之前呼叫length = size
,因为您可能已经猜到,sizeJokesArray
是异步的。
但是因为你已经在使用promises,所以修复很简单:
sizeJokesArray().then(fetchJokes);
如果您还没有完全理解承诺如何运作,也许https://developers.google.com/web/fundamentals/getting-started/primers/promises有帮助。