Ankit
Ankit

Reputation: 669

Response is set in dialogflow webhook but it returns that no response has been set

I am calling my dynamodb database from dialogflow. Following is the code for the intent:

app.intent('Survey ID', (conv) => {
    const ans = conv.parameters.any;
    let dbread = new aws.DynamoDB.DocumentClient();
    let read = function(){
      var parameters = {
          TableName: "DEV_SURVEY",
          Key:{
            "S_ID": ans
          }
       };
       dbread.get(parameters,function(err,data){
           if(err){
               console.log("error", JSON.stringify(err,null,2));
               conv.close('This is not a valid survey ID');
           }
           else{
               console.log("success", JSON.stringify(data,null,2));
               //conv.add('Hello');
               //Adding API here
            }
        })
    }
      read(); 
});

The calling data is working fine as the contents are being visible in the logs. But the response or any code which is being written after the console.log is causing error. The error is:

Error: No response has been set. Is this being used in an async call that was not returned as a promise to the intent handler?

Upvotes: 0

Views: 50

Answers (1)

Prisoner
Prisoner

Reputation: 50701

The issue is exactly what the error message says - you're making an asynchronous request, but you're not returning a Promise. This is further complicated since you're using callbacks instead of a Promise-based response. The callback does complete, so you see the console logs, but by the time it has completed, the original function has already returned and attempted to send a reply to

dbread.get() returns an AWS.Request object, which can be used to get a Promise. Moving your processing of the call to DynamoDB inside of a Promise handler, and returning the promise, and it might look something like this:

app.intent('Survey ID', (conv) => {
    const ans = conv.parameters.any;
    let dbread = new aws.DynamoDB.DocumentClient();
    const parameters = {
      TableName: "DEV_SURVEY",
      Key:{
        "S_ID": ans
      }
    };
    return dbread.get(parameters).promise()

      .then( data => {
               console.log("success", JSON.stringify(data,null,2));
               conv.add('Hello');
               //API here - make sure they continue to use Promises and .then()
      })

      .catch( err => {
        console.log("error", JSON.stringify(err,null,2));
        conv.close('This is not a valid survey ID');
      });
});

Upvotes: 2

Related Questions