我正在构建一个简单的琐事游戏,其中涉及从openTriviaDB API中提取一系列问题,然后逐一显示这些问题,以供用户回答。我有一个ES6 QUESTIONS
模块来处理(除其他事项外)问题数组初始化,还有一个PRESENTATION
模块来处理向用户显示问题。
相关代码为:
const QUESTIONS = (function questions(){
let questionArray;
function initializeQuestions(amount,category,mode){
if(amount > 20 || amount === /.e/gi) amount = 20;
if(amount < 5) amount = 5;
return new Promise((resolve,reject) => {
fetch(`https://opentdb.com/api.php?amount=${amount}&${category}&difficulty=${mode}&type=multiple&encode=url3986`)
.then(response => response.json())
.then(response => questionArray = response.results)
.then(() => resolve())
.catch(e => reject(`Error in initializing questions: ${e}`))
});
}
return{
initializeQuestions,questionArray
}
})();
export default QUESTIONS;
import QUESTIONS from "(filepath)"
const PRESENTATION = (function presentation(){
function displayNewScreen(){
if (count === QUESTIONS.questionArray.length){
newScreenAnimation(displayFinalScreen);
}else{
activateQuestionView();
newScreenAnimation(displayNextQuestion);
}
}
})();
export default PRESENTATION
问题是,当我尝试从questionArray
模块外部访问QUESTIONS
变量时,出现错误,如下所示:
QUESTIONS.initializeQuestions(QUESTION_AMOUNT.value,CATEGORY.value,e.target.textContent.toLowerCase())
.then(() => PRESENTATION.displayNewScreen());
Uncaught (in promise) TypeError: Cannot read property 'length' of undefined
at Object.displayNewScreen (presentation.js:138)
at eval (app.js:21).
如果我尝试从console.log()
函数中使用questionArray
initializeQuestions
来.then(() => console.log(questionArray)
的值,它将返回所需的值,但是如果我{{1} }从console.log(QUESTIONS.questionArray)
模块外部,返回未定义。
在我使用webpack时,起初我以为这可能是由于循环依赖问题造成的,但是即使我消除了这个问题,问题仍然存在(这是fetch调用包含在promise中的原因,消除了QUESTIONS
模块导入QUESTIONS
模块的需要。
如何解决此问题?