在函数外部访问变量

时间:2019-04-26 06:48:08

标签: node.js aws-lambda alexa-skills-kit alexa-app

我正在使用Node.js在lambda中为Amazon Alexa开发技能。

我已经全局声明了变量,并在函数中初始化并在函数外部访问它。但我收到未定义的错误。请帮忙。


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 个答案:

答案 0 :(得分:0)

我经常在这个论坛上寻找与类似问题有关的问题。关于Async-Await的文档不够多,或者对将Async-Await与回调函数一起使用有一些误解。

您的情况有两个问题。

  1. con.query是异步函数。因此,当您的回调函数被调用时,“ console.log(res);”应该已经执行过,因此res变量中没有任何定义。

  2. 您不能将回调与Aysnc-Await语法一起使用。您必须保证回调正确,并在Async函数中使用它才能获得预期的结果。

    Here is the example for it

答案 1 :(得分:0)

可能的解决方案是使用promisify方法,因为这种执行是异步的

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
    }
}