【问题标题】:dialogflow agent not ouputting text from inside HTTP request callback对话流代理不从 HTTP 请求回调中输出文本
【发布时间】:2018-05-28 06:29:56
【问题描述】:

我正在尝试从由欢迎意图触发的外部站点获取数据。现在我正在尝试向google.com 发送一个简单的GET 请求。

代理按预期工作,除非从请求回调内部调用。它有时有效,有时无效。

'use strict';    
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
process.env.DEBUG = 'dialogflow:debug'; 

exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response });

  function search(agent){

          var request = require("request");
          var options = {
            method: 'GET',
            url: 'http://google.com'
          };

          console.log("Before request");
          agent.add("Before request");

          request(options, function (error, response, body){
            console.log("Request completed");
            agent.add("Request completed");     //<- This line doesn't show in agent
            console.log("finished");            //<- This line shows in the log
          });

          console.log("Request sent");
          agent.add(`Request sent`);
  }

  let intentMap = new Map();
  intentMap.set('Default Welcome Intent', search);
  agent.handleRequest(intentMap);
});

我在日志中注意到消息"Function execution took 1697 ms, finished with status code: 200" 显示在消息"finished" 之前。我不知道这是否意味着该进程正在关闭并在此之后忽略 agent.add() 调用。

Image: firebase log console showing function excecution finished before request compelted

【问题讨论】:

    标签: node.js httprequest dialogflow-es


    【解决方案1】:

    问题在于回调/承诺。 您需要在搜索功能中返回一个承诺。

    function search(agent, query){
        return new Promise((resolve, reject) => {
          request.get(options, (error, response, body) => {
          .....
          agent.add(...)
          resolve();
         });
       });
    };
    

    原始答案可以在以下 Github issue 中找到:

    https://github.com/dialogflow/dialogflow-fulfillment-nodejs/issues/3

    编辑:

    从 DialogFlow 支持人员那里得到了一点帮助。建议的代码缺少一点变化才能正常工作:

    function search(agent, query){
      return new Promise((resolve, reject) => {
        request.get(options, (error, response, body) => {
          .....
          let output = agent.add(...)
          resolve(output);  //<- agent.add() should be passed as argument in resolve()
        });
      });
    };
    

    【讨论】:

    • 不,没用。 agent.add() 方法有效,但来自请求回调内部。我将添加有关问题的更新。
    • 我用非常简化的代码更新了我的问题。同样的代码,它有时显示代理输出,有时不显示。
    • 正如我之前提到的你的函数functionWithHTTPRequest(代理需要返回承诺)。否则代理(webhookclient 请求)已经被解析。你有没有尝试兑现承诺?此外,您需要在 promise 解决后合并所有 agent.add 命令。我猜你不能发送一个 agent.add 然后在请求回调中等待另一个 agent.add。
    • 您的代码非常接近解决方案。只是resolve(output) 中的参数丢失了。我仍然不明白代理管道中这个 Promises 的方式或原因,但现在它正在工作。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-13
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 2015-09-28
    相关资源
    最近更新 更多