【问题标题】:Node/Firebase onCall asynchronous function returnNode/Firebase onCall 异步函数返回
【发布时间】: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


    【解决方案1】:

    您上次 sn-p 中的方法不起作用:当您的 return gBody 运行来自 3rd 方 API 的回调时,尚未调用,因此 gBody 为空。

    正如 Cloud Functions 文档所说:

    要在异步操作后返回数据,请返回一个承诺。 Promise 返回的数据被发送回客户端。

    因此,您只需返回一个承诺,然后使用来自 3rd 方 API 的数据来解决该承诺。

    exports.submitMessage = functions.https.onCall((data, context) => {
      return new Promise(function(resolve, reject) {
        request({
          url: URL,
          method: "POST",
          json: true,
          body: queryJSON //A json variable I've built previously
        }, function (error, response, body) {
          if (error) {
            reject(error);
          } 
          else {
            resolve(body)
          } 
        });
      });
    });
    

    【讨论】:

    • 为帮助队友干杯!不过,我将如何在客户端处理此承诺?
    • promise 的结果以与普通 return 完全相同的方式发送回客户端。
    • Edit 很抱歉格式错误,我对这个论坛很陌生。我尝试过以下操作,但不起作用...submitMessage({message: userMessage{).then(function(result) { result.then(function(result) { console.log(result); }); });
    • 没关系,我没有意识到结果可以像常规 JSON 变量一样读取。 result.data 为您提供最初从 3rd 方 API 检索到的内容。为你的帮助伙伴干杯!!