Node.JS - 通过Alexa说出查询结果

时间:2018-02-05 14:45:51

标签: javascript mysql node.js variables alexa

我对编码非常陌生,我在这里打了一堵砖墙。我正在使用node.js的mysql模块,我想执行一个查询以在我的Alexa技能中使用。我的想法是Alexa会说出我的查询结果。如何将查询结果放在变量中,然后在我的“tell”命令中为Alexa引用该变量?

这是我到目前为止所得到的:

'LaunchRequest': function () {

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'myserver.amazonaws.com',
  user     : 'secret',
  password : 'secret',
  database : 'mydata',
  port     : '1433'
});

connection.query('SELECT `book` FROM `dbo.tblBibleBooks` WHERE `id` = "4"', function (error, results, fields) {

 });


  connection.end();
 this.emit(':tell', myvariable);

2 个答案:

答案 0 :(得分:0)

How can I place the query result in a variable这非常接近:

connection.query('SELECT `book` FROM `dbo.tblBibleBooks` WHERE `id` = "4"', 
function (error, results, fields) {
  this.emit(':tell', results);
});

是的。希望它有所帮助!

答案 1 :(得分:0)

  

如何将查询结果放在变量中,然后引用   Alexa的“tell”命令中的那个变量?

旧方式 - 绑定回调

您可以将this的上下文绑定到回调函数,以便将结果定向到.emit函数。为此,请使用function.bind在回调中设置this上下文:

connection.query('SELECT `book` FROM `dbo.tblBibleBooks` WHERE `id` = "4"', function (error, results, fields) {
  // handle if error or no result...
  this.emit(':tell', results);
}.bind(this));

新方式 - 使用箭头功能

如果您能够使用ES6,则可以使用箭头功能。它允许您在函数内部使用this但引用函数外部的上下文(它没有自己的this上下文):

connection.query('SELECT `book` FROM `dbo.tblBibleBooks` WHERE `id` = "4"', (error, results, fields) => {
  // handle if error or no result...
  this.emit(':tell', results);
});

读物/参考文献

在此处阅读有关回调的更多信息:

https://developer.mozilla.org/en-US/docs/Glossary/Callback_function

点击此处bind了解详情:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

在这里阅读更多箭头功能: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

在此处阅读有关ES6的更多信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_2015_support_in_Mozilla