我需要一个数据库的alexa应用程序,所以我设置和它很好地插入,但当我试图选择并保存它到一个变量的值保存到变量的对象对象而不是想要的值,我知道这可能是异步问题或解析问题,但我只是不能修复代码,一些帮助将是很酷的,
canHandle(handlerInput) {
return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
&& Alexa.getIntentName(handlerInput.requestEnvelope) === 'buscaIntent';
},
handle(handlerInput) {
const mysql = require('mysql');
const connection = mysql.createConnection
({
host: 'remotemysql.com',
user: 'RBb34534sd',
password: 'xxxxxxxxx',
database: 'RBsdfewrg'
});
var stat = connection.query('SELECT `spe` FROM `prueba` WHERE `nombre` LIKE "raichu" limit 1', function (err, result, fields) {
if (err) throw err;
console.log(result);
return result[0];
});
connection.end();
return handlerInput.responseBuilder
.speak("Busc " + stat)
.reprompt("reprompt buscar")
.getResponse();
}
}; ```发布于 2020-01-04 19:16:52
问题是,在将响应发送到Alexa服务之前,您并没有等待数据库查询完成。node.js中的请求是非阻塞的,这意味着您需要使用回调嵌套请求,或者利用Promises / async-await模式,以便在函数完全执行之前处理SQL查询。
您可以阅读更多关于转换用于SQL connection的内置库以支持Promises here的内容,或者使用像this这样已经有了包装器的库。
在任何一种情况下,最终结果都将被重构为如下所示:
canHandle(handlerInput) {
return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
&& Alexa.getIntentName(handlerInput.requestEnvelope) === 'buscaIntent';
},
async handle(handlerInput) {
const mysql = require('mysql2/promise');
const connection = await mysql.createConnection
({
host: 'remotemysql.com',
user: 'RBb34534sd',
password: 'xxxxxxxxx',
database: 'RBsdfewrg'
});
var stat = await connection.execute('SELECT `spe` FROM `prueba` WHERE `nombre` LIKE "raichu" limit 1', function (err, result, fields) {
if (err) throw err;
console.log(result);
return result[0];
});
return handlerInput.responseBuilder
.speak("Busc " + stat)
.reprompt("reprompt buscar")
.getResponse();
}另一篇文章描述了Alexa的异步调用请求here。
发布于 2019-12-30 21:32:09
我认为查询返回的是一个对象,您不能将该对象保留在语音中。检查对象内部的内容,如果在该对象内有您想要的字段,则通过stat.YourField进行访问。
https://stackoverflow.com/questions/59530018
复制相似问题