挂起的异步函数立即执行,而不是遵循await关键字



我不擅长Promises和异步功能,我想我不知道自己在做什么。对于智力竞赛应用程序,我尝试使用的逻辑是,当给出答案时,它应该将其背景更改为用户,以便他/她知道答案是正确的,3秒后,div应该被清除,当它们消失时,应该从可能的问题对象中删除当前问题,并给出一个新问题。然而,在我给出答案的那一刻,它立即删除了div,并在中间应该有一段时间的时候给我下一个问题。

如果有人能清理我的代码或解释为什么它不起作用,我会发自内心地感谢你!

我的代码:

const playTheGame = async () => {
//Takes the divs where the possible answers are stored
const divs = options.querySelectorAll('div');
for (let i = 1; i < options.childNodes.length; i++) {
const element = options.childNodes[i];
// Click on an answer so it can be evaluated
element.addEventListener('click', () => {
id = Array.from(divs).indexOf(element);
// If the answer is correct, background should become green
if (id === correct) {
console.log('answered correctly!')
divs[id].classList.add('correct');
} else {
console.log('answered correctly!')
}
// Function to delete the divs after 3 seconds
async function deleteDivs() {
for (const option of options.querySelectorAll('div')) {
setTimeout(option.remove(), 3000)
}
}
// Function to start the deleteDivs-function; remove the current question and give a new question
async function endHandler() {
await deleteDivs()
await availableQuestions.shift()
await newQuestion();
}
endHandler()
});
};
};

setTimeout只注册一个回调,并返回一个定时器id。setTimeoutiteself与Promiseasync/await无关;

您可以尝试这种方式从deleteDivs:返回Promise

// Function to delete all the divs after 3 seconds
async function deleteDivs() {
return new Promise((resolve) => {
setTimeout(() => {
for (const option of options.querySelectorAll("div")) {
option.remove();
}
resolve();
}, 3000);
});
}

最新更新