[英]Node JS - How can I get the value outside the function?
我试图在 function 之外获取变量“Ajuste”的值,因为我需要 Alexa 在另一个 function 的最后返回中说出来。
“Ajuste”变量的值应该在 function 之外的“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();
}
};
让所有方法通用的 scope 中的 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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.