Node JS - Как я могу получить значение вне функции? - PullRequest
0 голосов
/ 04 мая 2020

Я пытаюсь получить значение переменной "Ajuste" вне функции, потому что мне нужно, чтобы Alexa сказала это в последнем возврате другой функции.

Значение "Ajuste" переменная должна быть использована в переменной "speakOutput", которая находится за пределами этой функции, но, наконец, она показывает мне, что значение равно undefined.

Это фрагмент, с которым у меня возникают проблемы, соединение с базой данных Это нормально, и запрос также выполняется без проблем, потому что значение console.log(result.recordset [0] .Consecutive); это правильно.

var Inventario = {
  user: 'user',
  password: 'pass',
  server: 'server\\instance',
  database: 'db'
};

const InventarioIngresoIntentHandler = {
  canHandle(handlerInput) {
    return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest' &&
      Alexa.getIntentName(handlerInput.requestEnvelope) === 'InventarioIngresoIntent';
  },
  handle(handlerInput) {
    var DocInventario = handlerInput.requestEnvelope.request.intent.slots.Documento.value
    var Ajuste;
    sql.connect(Inventario, function(err) {
      if (err) console.log(err);
      var request = new sql.Request();
      request.query('select * from Ajuste Where ConsecutivoExterno =' + DocInventario, function(err, result) {
        if (err) console.log(err)
        console.log(result.recordset[0].Consecutivo);
        console.log(result.recordset[0].ConsecutivoExterno);
        Ajuste = result.recordset[0].Consecutivo;
        sql.close();
      })
    });
    const speakOutput = Ajuste + ', Correcto.' + DocInventario
    return handlerInput.responseBuilder
      .speak(speakOutput)
      .withSimpleCard(SkillName, speakOutput)
      .reprompt(speakOutput)
      .getResponse();
  }
};

1 Ответ

0 голосов
/ 04 мая 2020

пусть свойство Ajuste находится в области видимости, общей для всех методов. Я изменяю var на const, потому что var иногда ведет себя непредвиденно, потому что он не ограничен областью действия.

const InventarioIngresoIntentHandler = {
  Ajuste: undefined,
  showAjuste() {
    this.Ajuste = "New Value";
    console.log(this.Ajuste)
  },
  canHandle(handlerInput) {
    return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest' &&
      Alexa.getIntentName(handlerInput.requestEnvelope) === 'InventarioIngresoIntent';
  },
  handle(handlerInput) {
    const DocInventario = handlerInput.requestEnvelope.request.intent.slots.Documento.value
    
    sql.connect(Inventario, function(err) {
      if (err) console.log(err);
      const request = new sql.Request();
      request.query('select * from Ajuste Where ConsecutivoExterno =' + DocInventario, function(err, result) {
        if (err) console.log(err)
        
        this.Ajuste = result.recordset[0].Consecutivo;
        sql.close();
      })
    });
    const speakOutput = this.Ajuste + ', Correcto.' + DocInventario
    return handlerInput.responseBuilder
      .speak(speakOutput)
      .withSimpleCard(SkillName, speakOutput)
      .reprompt(speakOutput)
      .getResponse();
  }
};

InventarioIngresoIntentHandler.showAjuste()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...