0

I am developing a skill for Amazon Alexa in lambda using Node.js.

I've declared the variable globally, and initialised in function and accessing it outside the function. But I'm getting undefined error. Please help.


var res;
async function classSection(handlerInput){


  standard = handlerInput.requestEnvelope.request.intent.slots.Class.value;
  section = handlerInput.requestEnvelope.request.intent.slots.Section.value;

  var speechOutput = `Starting attendance for class ${standard}, section ${section}. <break time = "3s"/> 
  I will call the Names of the students, please say Present or Absent to Mark the attendance. <break time = "1s"/> Lets Start.  `;

    //getting the list of students from database
    con.connect(function(err){
        if(!err) {
            console.log("Database is connected");    
        } else {
            console.log("Error connecting database");    
        }
    });

    const sql = `SELECT StudentDetailID,StudentName FROM attendance_system.student_detail where student_detail.Class = ${standard} 
    and student_detail.Section = '${section}';`;

    console.log(sql);
     con.query(sql, function (err, result, fields) {
        con.end();

        if (!err){
            console.log(result);
            console.log("Table Data : "+result[1].StudentName);

            res = result[1].StudentName;
            console.log("Speech : "+ speechOutput + res);
            //Here in res I get the name of the student.   

        }
        else
    console.log('Error while performing Query.');
        });

    console.log(res);
//here I get undefined error.
 return handlerInput.responseBuilder
            .speak(speechOutput + res)
            .reprompt()
            .withSimpleCard('Attendance System',`Class : ${standard} \n Section : ${section}`)
            .getResponse();
}
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – CertainPerformance Apr 26 '19 at 06:48
  • Possbile duplicate of https://stackoverflow.com/questions/55687275/undefined-value-after-returning-an-array-of-values-from-a-mysql-query-in-a-diffe/55688488#55688488 – Sreehari Apr 26 '19 at 07:11

2 Answers2

0

I am looking questions related to similar problem very often in this forum. Either the documentation on Async-Await is not sufficient or there is some misunderstanding about the usage of Async-Await with callback functions.

There are 2 problems in your case.

  1. con.query is Asynchronous function. So, by the time the your callback function is called, 'console.log(res);' would have already executed and hence nothing is defined in res variable.

  2. You cannot use callback with Aysnc-Await syntax. You have to promisify your callback and use it in Async function to get the expected result.

    Here is the example for it

Sreehari
  • 1,328
  • 11
  • 29
0

Maybe a possible solution was use the promisify method, because of this execution is asynchronise

const promisify = require('util').promisify

async function classSection(handlerInput){

    try {
        standard = handlerInput.requestEnvelope.request.intent.slots.Class.value;
        section = handlerInput.requestEnvelope.request.intent.slots.Section.value;

        var speechOutput = `Starting attendance for class ${standard}, section ${section}. <break time = "3s"/>
        I will call the Names of the students, please say Present or Absent to Mark the attendance. <break time = "1s"/> Lets Start.  `;

        //getting the list of students from database
        await promisify(con.connect)();

        const sql = `SELECT StudentDetailID,StudentName FROM attendance_system.student_detail where student_detail.Class = ${standard}
        and student_detail.Section = '${section}';`;

        console.log(sql);

        const result = await promisify(con.query)(sql)

        console.log(result);
        console.log("Table Data : "+result[1].StudentName);

        const res = result[1].StudentName;
        console.log("Speech : "+ speechOutput + res);
        //Here in res I get the name of the student.

        console.log(res);

        //here I get undefined error.
        return handlerInput.responseBuilder
                    .speak(speechOutput + res)
                    .reprompt()
                    .withSimpleCard('Attendance System',`Class : ${standard} \n Section : ${section}`)
                    .getResponse();
    } catch (err) {
        console.log('Some Error was throwed', err);
        throw err;
    } finally {
        if (con.isConnect()) con.end() // i dont know if isConnect exists
    }
}