我正在尝试连接到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);
}
}
);
}
请帮我解决我可能做错的事。另一件事是,我是一个noob当谈到节点js。
提前谢谢!!
1条答案
按热度按时间dvtswwa31#
问题是,如果您使用的是异步函数,那么您的意图处理程序还必须返回一个承诺。你把答复作为答复的一部分发送是不够的
then()
条款,您还必须归还then()
是的一部分。对你来说,这看起来相当容易。在
getBalance()
函数,然后返回callDB().then().catch()
结果,这是一个承诺(then()
和` catch()返回一个承诺)