I am writing a handler for an intent to generate a PDF. This API accepts a POST request with the JSON data and returns a link to the generated PDF. The intent triggers this
If you are doing async calls, your handler function needs to return a Promise. Otherwise the handler dispatcher doesn't know there is an async call and will end immediately after the function returns.
The easiest way to use promises with network calls is to use a package such as request-promise-native. Using this, your code might look something like:
var options = {
uri: url,
method: 'POST',
json: true,
headers: { ... }
};
return rp(options)
.then( body => {
var val = body.someParameter;
var msg = `The value is ${val}`;
agent.add( msg );
});
If you really wanted to keep using xhr, you need to wrap it in a Promise. Possibly something like
return new Promise( (resolve,reject) => {
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
// ... other XMLHttpRequest setup here
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
agent.add(json.response);
resolve();
}
};
});