So this is the code for yelp-fusion node.js API used in dialogflow v2.
Problem:
agent.add(response.jsonBody.businesses[0].name);
which should make the bot say the name of the business doesnt actually run even though the code is there.
From research, other answers mentioned the need to use the fat arrow => in this javascript promises.
However, it is already being used. The code inside .then() isnt running, except for console.log, which does run.
Could anyone advice on what i can do to run methods inside javascript promises? Or other alternatives? Much appreciated. Thanks!
client below is the yelp API client.
agent is a webhookclient in dialogflow. agent.add() works when executed outside of this code below.
client.search({
term:'Four Barrel Coffee',
location: 'san francisco, ca'
}).then(response => {
//res = response.jsonBody.businesses[0].name; //*not assigned!
console.log(response.jsonBody.businesses[0].name);
agent.add(response.jsonBody.businesses[0].name); //*nothing!
}).catch(e => {
console.log(e);
});
You have half the solution. It isn't so much to use the fat-arrow, it is that you're dealing with asynchronous functions (the client.search
call) and that when you use async functions with the dialogflow-fulfillment library, you need to use Promises.
Specifically - you need to return a Promise so the calling function knows that it has to wait for all the then()
clauses to finish in order to send the reply.
You don't show your entire function, but you can probably do it by adding a few return
statements. Possibly something like this:
return client.search({
term:'Four Barrel Coffee',
location: 'san francisco, ca'
}).then(response => {
return agent.add(response.jsonBody.businesses[0].name);
}).catch(e => {
console.log(e);
return Promise.reject( e );
});