node.js - dialogflow 代理不从 HTTP 请求回调中输出文本

标签 node.js httprequest dialogflow-es

我正在尝试从欢迎意图触发的外部站点获取数据。现在我正在尝试向 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 take 1697 ms, finished with status code: 200” 显示在消息 “finished” 之前。我不知道这是否意味着该进程正在关闭并忽略在那之后的 agent.add() 调用。

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

最佳答案

问题在于回调/ promise 。 您需要在搜索函数中返回一个 promise 。

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()
    });
  });
};

关于node.js - dialogflow 代理不从 HTTP 请求回调中输出文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50560352/

相关文章:

node.js - Node-sass 找不到 Compass 导入

javascript - eslint 禁用扩展覆盖

java - 如何更新印度铁路网站中添加的 PNR 验证码

c# - 为什么 Fiddler 的 Http 请求非常快

node.js - NodeJS - 从固定 HTTP 端点流式传输 MP3 音频播放列表

javascript - 在 Node 服务器和前端处理 JSON 响应

c# - 如何检测移动类型和移动请求?

javascript - Dialogflow 复合实体参数在不应定义时未定义

firebase - 如何在heroku上为Google Assistant部署Firebase功能

python - 对话流 : manage several credentials for several agents