Dialogflow NodeJs Fulfillment V2 - webhook method call ends before completing callback

試著忘記壹切 提交于 2019-11-28 14:25:15

You need to return a promise in your handler function. function handlers support promises now so you can return a promise and process things like http requests in the promise. Here is an example of using the request library:

function dialogflowHanlderWithRequest(agent) {
  return new Promise((resolve, reject) => {
    request.get(options, (error, response, body) => {
      JSON.parse(body)
      // processing code
      agent.add(...)
      resolve();
    });
  });
};

You can also move the HTTP call to another function that returns a promise. Here is an example with the axios library:

function dialogflowHandlerWithAxios(agent) {
  return callApi('www.google.com').then(response => {
    agent.add('My response');
  }).catch (error => {
    // do something
  })
};

function callApi(url) {
    return axios.get(url);
}

An example using then-request:

const thenRequest = require('then-request');

function callApi(resolve){

    var req = thenRequest('POST', 'https://api_url_here...',{
      headers: 
       { 
        '.....': '....'
       }
    });

    req.done(function (res) {
        ....
        agent.add("Some text goes here...");
        ...
        resolve();
    });     
}

Fire the request:

return new Promise((resolve, reject) => { 
    callApi(resolve); 
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!