Return Asynchronous responses from #dialogflow-fulfillment
If you are writing a Dialogflow webhook in node, you’re probably using dialogflow-fulfillment , and if you’re reading this post, you’ve run into the issue where DialogFlow is not returning properly when you carry out an asynchronous call.
Let’s see a typical syncronous case first;
intentMap.set(‘Default Welcome Intent’, welcome);
….
function welcome(agent) {
agent.add(“Welcome”);
}
Which returns Welcome, when the Default Welcome Intent is fired.
In this next typical use case, where I want to record failed queries, i.e. queries that trigger the fallback intent in a database. The Database is asyncronous, so it will fire a callback once the data is stored.
intentMap.set(‘Default Fallback Intent’, fallback);
….
function fallback(agent) {
database.recordFailure(request.body.queryResult.queryText, function(text)
{
agent.add(“Sorry, I couldn’t help you”);
});
}
Now, if you run this with the fallback intent, then you may notice that the data is stored in the database, but you get an error response back, rather than the “Sorry, I couldn’t help you” message
The trick is, to wrap the function in a promise like so;
function fallback(agent) {
return new Promise ( (resolve, reject) => {
database.recordFailure(request.body.queryResult.queryText, function(text)
{
agent.add(text);
return resolve();
});
});
}
And call resolve() once you’re ready to reply to the user.
Hi, I am trying to do similar thing in a setTimeOut within promise, want to trigger a custom event once the time is complete. console.log works but event is not triggered. Please help.
Below is the code snippet:
function payment(agent){
const delay = t => new Promise(resolve => setTimeout(resolve, t));
return delay(5000).then(() => {console.log(‘Hello’);
agent.setFollowupEvent(‘payment_completed’);
});
}
LikeLike
Hey Have you resolve this ?
can you let me know if this is possible delay in dialogflow response
LikeLike