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
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);
});
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);
}