首页 > 解决方案 > 如何在云函数中调用 API?

问题描述

我正在使用 Dialogflow 和 Cloud Functions 在 Google 聊天机器人上开发 Actions。运行时是 Node.js 6。

为什么这个函数返回空字符串?

function getJSON(url) {
  var json = "";
  var request = https.get(url, function(response) {
    var body = "";
    json = 'response';
    response.on("data", function(chunk) {
      body += chunk;
      json = 'chunk';
    });
    response.on("end", function() {
      if (response.statusCode == 200) {
        try {
          json = 'JSON.parse(body)';
          return json;
        } catch (error) {
          json = 'Error1';
          return json;
        }
      } else {
        json = 'Error2';
        return json;
      }
    });
  });
  return json;
}

这是我要访问 json 数据的意图:

app.intent('test', (conv) => {
conv.user.storage.test = 'no change';
const rp = require("request-promise-native");
var options = {
    uri: 'https://teamtreehouse.com/joshtimonen.json',
    headers: {
        'User-Agent': 'Request-Promise'
    },
    json: true // Automatically parses the JSON string in the response
};

rp(options)
    .then(function (user) {
        conv.user.storage.test = user.name;
    })
    .catch(function (err) {
        conv.user.storage.test = 'fail';
    });
conv.ask(conv.user.storage.test);
});

标签: node.jsgoogle-cloud-platformgoogle-cloud-functionsdialogflow-esdialogflow-es-fulfillment

解决方案


该函数返回空字符串,因为https设置了一个回调函数,但程序流程在调用回调之前继续执行 return 语句。

通常,在使用 Dialogflow Intent 处理程序时,您应该返回 Promise 而不是使用回调或事件。考虑使用request-promise-native代替。

两个澄清点:

  • 必须返回 Promise。否则 Dialogflow 将假定 Handler 已完成。如果您返回 Promise,它将等待 Promise 完成。
  • 您要发回的所有内容都必须在then()块内完成。这包括设置任何响应。该then()块在异步操作(Web API 调用)完成后运行。所以这将有调用的结果,您可以在调用中将这些结果返回给conv.ask().

所以它可能看起来像这样:

  return rp(options)
    .then(function (user) {
      conv.add('your name is '+user.name);
    })
    .catch(function (err) {
      conv.add('something went wrong '+err);
    });

推荐阅读