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

后端 未结 2 1366
旧巷少年郎
旧巷少年郎 2020-12-12 03:50

I am developing a Dialogflow webhook using dialogflow-fulfillment-nodejs client to find temperature for a city. While using the services to fetch the temper

相关标签:
2条回答
  • 2020-12-12 04:04

    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); 
    });
    
    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
提交回复
热议问题