node.js - 如何在云函数中调用 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);
});
解决方案
该函数返回空字符串,因为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);
});
推荐阅读
- twig - 在 twig current 中执行 twig var
- python - 如何在 Pytorch 中为我的模型找到混淆矩阵和绘图
- r - 多个滚动分位数的高效计算
- linux - Kubernetes 中是否有任何选项可以在特定的 cgroup 目录中运行 pod?
- stream - 在终止操作中使用流 API 时出现错误
- c# - 您可以从 C# 控制台复制彩色文本吗?
- c# - 在 C# 中反序列化复杂对象
- powershell - 用于跳转到下一个文件夹的 Powershell 命令
- java - 没有可用的“org.springframework.jms.core.JmsTemplate”类型的合格 bean
- javascript - 单击按钮更改背景