问题描述
我正在尝试进行自己的 google 操作,并且想调用外部 api 以获取响应。
这是我的代码:
const { conversation } = require('@assistant/conversation');
const functions = require('firebase-functions');
const app = conversation({debug:true});
const https = require('https');
app.handle('Tester',conv => {
// Implement your code here
conv.add("ok it works");
});
app.handle('Tester2',conv => {
// Implement your code here
let url = 'https://jsonplaceholder.typicode.com/users?_limit=2';
//const url = "https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22";
http_req(url).then((message)=> {
console.log(message[0].name);
conv.add(message[0].name);
//return Promise.resolve();
});
});
function http_req(url) {
return new Promise((resolve,reject) => {
https.get(url,function(resp) {
var json = "";
resp.on("data",function(chunk) {
//console.log("received JSON response: " + chunk);
json += chunk;
});
resp.on("end",function() {
let jsonData = JSON.parse(json);
console.log(jsonData[0].name);
resolve(jsonData);
});
}).on("error",(err) => {
reject("Error: " + err.message);
});
});
}
exports.ActionsOnGoogleFulfillment = functions.https.onRequest(app);
错误文本:
Error: Response has already been sent. Is this being used in an async call that was not returned as a promise to the intent handler?
问题是助手不会说conv.add(message[0].name); (显然它有一个价值)
提前致谢!
解决方法
此错误消息告诉您几乎所有您需要知道的信息!您的 对 con.add() 的调用确实在异步调用中使用( 回调链接到您从 http_req 创建的 Promise),并且您 确实没有返回那个承诺。
这是正在发生的事情:
Google 调用您的“Tester2”处理程序
你通过 http_req 发起一个异步 HTTP 请求,封装在一个 承诺
您的函数在 HTTP 请求之前完成
Google 发现您没有从处理程序返回任何内容,并且 假设你已经完成,所以它发送响应
HTTP 请求完成并且其 Promise 解析,调用您的代码 由 then() 函数附加
这里的简单解决方案是返回您创建的 Promise http_req(...).then(...) 代码,所以谷歌会知道你不只是 完成了,它应该等待 Promise 解决之前 发送响应。
如果你可以使用 async/await 就更清楚了:
app.handle('Tester2',async conv => {
// Implement your code here
let url = 'https://jsonplaceholder.typicode.com/users?_limit=2';
//const url = "https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22";
const message = await http_req(url);
console.log(message[0].name);
conv.add(message[0].name);
});