mysql - 将查询结果保存到变量 Alexa Skills Json 中

标签 mysql json variables alexa-skills-kit alexa-skill

我需要一个用于 Alexa 应用程序的数据库,所以我设置并很好地插入,但是当我尝试选择并将其保存到变量时,保存到变量的值是 [Object Object] 而不是想要的值,我知道这可能是异步问题或解析问题,但我只是无法修复代码,一些帮助会很酷,

    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();


    }
}; ```

最佳答案

问题在于,您没有等待数据库查询完成就将响应发送到 Alexa 服务。 Node.js 中的请求是非阻塞的,这意味着您需要使用回调嵌套请求,或者利用 Promises/async-await 模式,以便在函数完全执行之前处理 SQL 查询。

您可以阅读有关将 SQL 连接的内置库转换为支持 Promise 的更多信息 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 .

关于mysql - 将查询结果保存到变量 Alexa Skills Json 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59530018/

相关文章:

php - mysql查询缩进子项并对所有子项进行分组

php - 显示mysql数据时出现重复列

android - 在Android中使用Volley进行错误处理

ios - iPhone游戏设计中的单例/全局变量

PHP更新查询

mysql - 反对使用 ENUM 的理由是什么?

python - 从 UTF-8 编码的字节串中读取 JSON 数据

javascript - 在 React 中嵌套三个组件

c++ - 按作用域获取变量

arrays - bash循环分配变量值而不覆盖先前声明的变量