首页 > 解决方案 > 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);
    });

标签: javascriptnode.jsdialogflow-esyelpyelp-fusion-api

解决方案


你有一半的解决方案。使用胖箭头并没有那么多,而是您正在处理异步函数(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 );
});

推荐阅读