Доступ к переменной вне функции - PullRequest
0 голосов
/ 26 апреля 2019

Я разрабатываю навык для Amazon Alexa в лямбде, используя Node.js.

Я объявил переменную глобально, инициализировал в функции и получил доступ к ней вне функции. Но я получаю неопределенную ошибку. Пожалуйста помоги.


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 голосов
/ 26 апреля 2019

Возможно, возможным решением было использование метода 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
    }
}

0 голосов
/ 26 апреля 2019

Я очень часто просматриваю вопросы, связанные с подобной проблемой, на этом форуме.Либо документации по Async-Await недостаточно, либо существует некоторое недопонимание относительно использования Async-Await с функциями обратного вызова.

В вашем случае есть 2 проблемы.

  1. con.query - асинхронная функция.Итак, к тому времени, когда вызывается ваша функция обратного вызова, 'console.log (res);'был бы уже выполнен, и, следовательно, ничего не определено в переменной res.

  2. Вы не можете использовать обратный вызов с синтаксисом Aysnc-Await.Вы должны обещать свой обратный вызов и использовать его в асинхронной функции, чтобы получить ожидаемый результат.

    Вот пример для него

...