[英]How to fetch data using Dialogflow Fulfillment from Firebase
I'm currently working on a FAQ chatbot. 我目前正在使用FAQ聊天机器人。
Some of the answers will be specific depending on the parameter of the user, so I decided to use Webhook so I can fetch response from my firebase database. 根据用户的参数,某些答案将是特定的,因此我决定使用Webhook,以便可以从Firebase数据库获取响应。
After some research, I've noticed that Dialogflow works asynchronously and I had to use Promise, but I'm still not able to make the response dynamic and synchronous. 经过一些研究,我注意到Dialogflow是异步工作的,因此我不得不使用Promise,但是我仍然无法使响应动态和同步。
Here's my code: 这是我的代码:
function fetch_data(param)
{
return function(agent)
{
console.log("Fetching informations ...");
var result = database_call();
result.then(function(response)
{
agent.add(response);
});
agent.add("Timeout !")
};
}
function database_call()
{
return new Promise((resolve, reject) => {
var ref = db.ref("test/");
var refTest = ref.child('test');
refTest.on("value", function(snapshot)
{
console.log(snapshot.val());
resolve(snapshot.val());
});
agent.add("[TIMEOUT] Cannot fetch data !")
});
}
I always get the message: Cannot fetch data, despite the Promise function. 我总是收到消息:尽管有Promise功能,但仍无法获取数据。
On my log, I notice that the data are always printed few seconds after the "timeout" message. 在我的日志中,我注意到数据总是在“超时”消息后几秒钟打印出来。
Because it is async it will always print the timeout. 因为它是异步的,所以它将始终打印超时。
Move the timeouts to the fail case for the ref test. 将超时移至参考测试失败的情况。
refTest.on("value", function(snapshot)
{
console.log(snapshot.val());
resolve(snapshot.val());
});
refTest.on("error", function(snapshot)
{
agent.add("[TIMEOUT] Cannot fetch data !")
reject();
});
Then you can catch the error. 然后,您可以捕获该错误。
result.then(function(response)
{
agent.add(response);
}).catch(() => {
agent.add("Timeout !")
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.