Node JS-如何在函数外部获取值?

问题描述 投票:0回答:1

我正在尝试在函数外获取变量“ Ajuste”的值,因为我需要Alexa在另一个函数的最后一次返回中说出来。

应该在该函数之外的“ speakOutput”变量中使用“ Ajuste”变量的值,但最后它向我显示该值为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();
  }
};
javascript node.js sql-server alexa-skills-kit
1个回答
0
投票

将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()
© www.soinside.com 2019 - 2024. All rights reserved.