【发布时间】:2026-02-24 12:35:01
【问题描述】:
用户在聊天客户端(网站)中键入消息。此消息被发送到在 firebase 上设置的云功能。然后,云函数查询返回响应的第 3 方 API。此响应需要发送回客户端才能显示。
所以基本上我的客户会像这样调用云函数...
var submitMessage = firebase.functions().httpsCallable('submitMessage');
submitMessage({message: userMessage}).thenfunction(result) {
//Process result
});
我的云功能是这样的……
exports.submitMessage = functions.https.onCall((data, context) => {
request({
url: URL,
method: "POST",
json: true,
body: queryJSON //A json variable I've built previously
}, function (error, response, body) {
//Processes the result (which is in the body of the return)
});
return {response: "Test return"};
});
我已经包含了请求包,并且 API 调用本身运行良好。我可以从请求的返回函数中将结果打印到控制台。但是,显然因为请求是异步的,我不能只创建一个全局变量并将结果主体分配给它。我已经看到您可以在请求完成后调用回调函数。但是,我需要以某种方式将其传递给云函数返回值。所以简单地说,我需要这样做......
exports.submitMessage = functions.https.onCall((data, context) => {
var gBody;
request({
url: URL,
method: "POST",
json: true,
body: queryJSON //A json variable I've built previously
}, function (error, response, body) {
gBody = body;
});
return gBody;
});
(是的,我知道这篇文章...How do I return the response from an asynchronous call? 但是是的,正如我所说,我需要将变量范围放在云函数本身内,以便我能够将值返回给客户端。要么我不明白该帖子中使用的方法,或者它没有完成我的要求)
【问题讨论】:
标签: node.js firebase google-cloud-functions