javascript - javascript 中的方法承诺不在对话框流上运行
问题描述
所以这是 dialogflow v2 中使用的 yelp-fusion node.js API 的代码。
问题:
agent.add(response.jsonBody.businesses[0].name);
这应该让机器人说出企业名称实际上并没有运行,即使代码在那里。
根据研究,其他答案提到需要在这个 javascript 承诺中使用胖箭头 =>。
但是,它已经在使用。.then() 中的代码没有运行,除了 console.log,它确实运行。
任何人都可以就我可以做些什么来运行 javascript 承诺中的方法提供建议吗?还是其他替代方案?非常感激。谢谢!
下面的客户端是 yelp API 客户端。
agent 是 dialogflow 中的一个 webhookclient。agent.add() 在以下代码之外执行时有效。
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);
});
解决方案
你有一半的解决方案。使用胖箭头并没有那么多,而是您正在处理异步函数(client.search
调用),并且当您将异步函数与 dialogflow-fulfillment 库一起使用时,您需要使用 Promises。
具体来说 - 您需要返回一个 Promise 以便调用函数知道它必须等待所有then()
子句完成才能发送回复。
你没有展示你的整个函数,但你可以通过添加一些return
语句来做到这一点。可能是这样的:
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 );
});
推荐阅读
- javascript - 使用 Javascript 仅将选定的数组数据发送到另一个数组
- javascript - 是否可以将javascript值设置为
- android - 如何在 Android 应用程序中永久禁用 NDEF 标记发现,而不仅仅是针对 Activity?
- mongodb - flask_pymongo 无法使用 auth 访问 mongodb
- android - 在 SpannableStringBuilder getSpans() 中添加额外的行
- c# - 如何在日本日历选择器中更改年份格式
- python - 我应该如何测试循环中调用了多个函数?
- java - 如何读取不应包含“”或'或新行的csv文件,然后将修改后的csv插入数据库
- reactjs - react-leaflet mapboxgl集成不起作用
- mysql - SQL除法运算符及其在Mysql中的实现