dimanche 25 avril 2021

node - TypeError: Cannot read property 'question' of undefined

I have a problem with a cli app that I'm converting to client/server app.

I have a function in the class I wrote that will manage the random extracion of some questions. Sometimes I've noticed that the function fails to extract questions and I get this error

/Users/dev/Desktop/demo/demo-gui.js:77
                question: this.questions[n].question,
                                            ^

TypeError: Cannot read property 'question' of undefined
    at DemoGUI.extractQuestions (/Users/dev/Desktop/demo/demo-gui.js:77:45)
    at /Users/dev/Desktop/demo/demo-gui.js:51:18
    at Layer.handle [as handle_request] (/Users/dev/Desktop/demo/node_modules/express/lib/router/layer.js:95:5)
    at next (/Users/dev/Desktop/demo/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/Users/dev/Desktop/demo/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/Users/dev/Desktop/demo/node_modules/express/lib/router/layer.js:95:5)
    at /Users/dev/Desktop/demo/node_modules/express/lib/router/index.js:281:22
    at Function.process_params (/Users/dev/Desktop/demo/node_modules/express/lib/router/index.js:335:12)
    at next (/Users/dev/Desktop/demo/node_modules/express/lib/router/index.js:275:10)
    at urlencodedParser (/Users/dev/Desktop/demo/node_modules/body-parser/lib/types/urlencoded.js:91:7)

this is the method of the class that cause the problem

    async extractQuestions(){
        this.askQuestions = [];
        this.questionsAnswers = [];


        for(let i = 0; i < 10; i++){
            let n = chance.integer({min: 0, max: this.questions.length});

            this.askQuestions.push({
                questionIndex: n,
                question: this.questions[n].question,
                choices: this.questions[n].possibleAnswers
            });

            this.questionsAnswers.push({
                index: n,
                correctAnswer: this.questions[n].correctAnswer 
            });
        }
        //this.maxScore = Math.floor( 5 * 10 );
    }

the questions are loaded from a json file that is loaded in constructor of the class

    constructor(questionsFile, uiResources){
        this.questionsData = fs.readFileSync(questionsFile, {encoding: 'utf-8'});
        this.questions = JSON.parse(this.questionsData);
        this.uiResources = uiResources;
        this.app = express();
    }

Is there a way to fix this problem?




Aucun commentaire:

Enregistrer un commentaire