节点/ Firebase onCall异步函数返回

Bul*_*acy 4 node.js firebase google-cloud-functions

用户在聊天客户端(网站)中输入消息。此消息将发送到在Firebase上设置的云功能。然后,云功能查询返回响应的第三方API。该响应需要发送回客户端进行显示。

所以基本上我的客户像这样调用云功能...

var submitMessage = firebase.functions().httpsCallable('submitMessage');
submitMessage({message: userMessage}).thenfunction(result) {
  //Process result
});
Run Code Online (Sandbox Code Playgroud)

我的云功能看起来像这样...

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"};
});
Run Code Online (Sandbox Code Playgroud)

我已经包含了请求包,并且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;
});
Run Code Online (Sandbox Code Playgroud)

(是的,我知道这篇文章... 我该如何从异步调用返回响应?但是是的,正如我所说,我需要变量作用域位于云函数本身内,以便能够将值返回给客户。要么我不理解该帖子中使用的方法,要么不满足我的要求)

Fra*_*len 6

您上一个代码段中的方法不起作用:到您return gBody运行第3方API的回调时,尚未被调用,因此gBody为空。

正如Cloud Functions文档所说:

要在异步操作后返回数据,请返回promise。承诺返回的数据将发送回客户端。

因此,您只需返回一个承诺,然后再使用第三方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)
      } 
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

  • 承诺的结果以与常规“返回”完全相同的方式发送回客户端。 (3认同)