mysql - 无法通过 Dialogflow API V2 DB 调用中的 Promise 获得所需的结果
问题描述
我正在尝试连接到 MySQL 数据库,获取结果并将其传递给代理以显示给用户。由于 DB Query 是异步的,我使用 Promise 来获取回调并在解析数据后发送响应。我确实在日志中得到了响应,但函数执行在此之前结束,它似乎没有等待then调用。
这是代码:
var sqlQuery = '';
var dbResults = '';
exports.dialogflowFirebaseFulfillment =
functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
var reply = '';
function welcome(agent) {
agent.add(`Welcome to my agent!`);
}
function fallback(agent) {
agent.add(`I didn't understand`);
agent.add(`I'm sorry, can you try again?`);
}
function getBalance(){
sqlQuery = 'select * from master_balance where account_no = \'1234567\'';
callDB().then((results) => {
var balance_type = request.body.queryResult.parameters['balance_type'];
if(balance_type == 'SMS'){
console.log('In SMS');
reply = 'You have '+ results[0].bal_sms +' SMS left in your account';
}
else if(balance_type == 'Voice'){
console.log('In Voice-- from DB--'+results[0].bal_call);
reply = 'Your Voice balance is $ '+results[0].bal_call;
}
else if(balance_type == 'Data'){
console.log('In Data');
reply = 'You have '+results[0].bal_data +' MB left in your account';
}
else{
console.log('In Ahh');
reply = 'Ahh, there seems to be some issue. Please wait';
}
agent.add(reply);
return 1;
}).catch((error) => {
console.log('in catch----'+error);
});
return 1;
}
let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('Default Fallback Intent', fallback);
intentMap.set('Query.Balance', getBalance);
agent.handleRequest(intentMap);
});
function callDB() {
return new Promise((resolve, reject) => {
console.log('-- In callDB--'+sqlQuery);
try {
var connection = mysql.createConnection({
socketPath: '/cloudsql/' + connectionName,
user: dbUser,
password: dbPass,
database: dbName
});
connection.query(sqlQuery, function (error, results, fields) {
if (!error) {
console.log('--In no error 2--'+results[0]);
resolve(results);
} else {
let output = {'speech': 'Error. Query Failed.', 'displayText': 'Error. Query Failed.'};
console.log('--- in else----'+error);
reject(results);
}
});
connection.end();
} catch (err) {
let results = {'speech': 'try-cacth block error', 'displayText': 'try-cacth block error'};
console.log(results);
reject(results);
}
}
);
}
请帮助我解决我可能做错的事情。另一件事是,当谈到 Node JS 时,我是个菜鸟。
提前致谢 !!
解决方案
问题是,如果您使用的是异步函数,那么您的意图处理程序也必须返回一个 Promise。then()
将回复作为子句的一部分发送是不够的,您还必须返回作为一部分的 Promise then()
。
在您的情况下,这看起来相当容易。在getBalance()
函数中,您将返回callDB().then().catch()
结果,这是一个 Promise。(then()
并且 `catch() 返回一个 Promise)
return callDB().then((results) => {
....
推荐阅读
- python - 无法在 Python 3 中安装 hmmlearn
- c - 为什么free()总是触发断点
- c# - 我收到错误:在 MVVMLight 应用程序中从一个页面移动到另一个页面时的名称范围内找不到名称
- c# - 如何列出 Gtk.Treeview 的所有行
- android - 自定义类中的 Snackbar 未显示
- javascript - 是否可以同时使用具有多个预设的 Jest?
- docker - 如何在 docker FROM node:9.11.2-alpine 上安装纱线?
- rust - 如何使用 Serde 的自定义(反)序列化来更新任意输入的子集?
- r - 无法理解输出递归包
- python - np.where 返回一个空数组,其中包含 numpy 数组